user3461957
user3461957

Reputation: 163

Why I am getting `incompatible types error`?

Here is the code:

double[] hundredElementsMillionArray = new double[10000000]; 

        for(double ii=0;ii<10000000;ii++){
            hundredElementsMillionArray[ii] = ii;
        }

I am getting following error:

incompatible types: possible lossy conversion from double to int

though no int has been used in the code. Why is that so?

Upvotes: 1

Views: 67

Answers (2)

Rustam
Rustam

Reputation: 6515

the array index can not be float or double it must be integer so you must typecast to int as hundredElementsMillionArray[(int)ii] or best solution would be you should use index variable as int type.

Upvotes: 1

Eran
Eran

Reputation: 393771

The index of an array is always an int, so hundredElementsMillionArray[ii] would require to cast ii to int, but since such a conversion may cause a loss of information, it's not allowed without an explicit cast.

This would pass compilation:

double[] hundredElementsMillionArray = new double[10000000]; 
for(double ii=0;ii<10000000;ii++){
    hundredElementsMillionArray[(int) ii] = ii;
}

This would also pass compilation :

double[] hundredElementsMillionArray = new double[10000000]; 
for(int ii=0;ii<10000000;ii++){
    hundredElementsMillionArray[ii] = ii;
}

Upvotes: 3

Related Questions