[quote=camilolopes][quote=caduengenheiro]reparem este código:
[code]
int [][] testeInt = {{1,2,3},{4,5},{6}};
for(long x:testeInt[0]) {
System.out.println(x);
}
[/code]
Funciona beleza…
agora se voce mudar um pouquinho e fizer
[code]
int [][] testeInt = {{1,2,3},{4,5},{6}};
for(long x[]:testeInt) {
System.out.println(x);
}
[/code]
gera erro de compilação. Alguém se arrisca a dizer o por que!
int myInt = 10;
long myLong;
myLong = myInt;
System.out.println(myLong);
abraços[/quote]
O ERRo pq tenho tipos diferente dentro do for… isso nao é permitido… por isso que dar erro… long X int. to certo?[/quote]
Exatamente!
Mas tem-se que enteder o porque!
Vejamos:
[code] int myInt = 10;
long myLong;
myLong = myInt;
System.out.println(myLong);[/code]
Roda perfeito, pois um “long” aceita “int”, já que jamais teremos perda de precisão.
Mas…
[code] int myInt = 10;
long myLong;
// Existe uma conversão implícita
myLong = myInt;
System.out.println(myLong); // compiles and run fine!
int[] arrInt = {1,2,3};
// Type mismatch: cannot convert from int[] to long[]
// long[] arrLong = arrInt;
// Cannot cast from int[] to long[]
// long[] arrLong = (long[]) arrInt;[/code]
Você não pode fazer cast porque infrige a seguinte regra:
to cast an object reference to an array type reference, the object must be an array of a component type that is compatible with the component type of the array type reference
os objetos “arrInt” e “arrLong” não são compatíveis!
Agora se fosse:
[code] Integer[] arrInteger = {new Integer(1), new Integer(2), new Integer(3)};
for (Number number : arrInteger)
{
System.out.println(number);
}[/code]
Não teria problemas pois “Integer” IS-A “Number”
Repare que os tipos são diferentes, mas nem por isso ocorre erro, nem de compilacao nem de run-time