user2347921
user2347921

Reputation: 83

Java - "for-loop" - incompatible types

void testK(ArrayList list) {
        for (int y= list.size() ; y > 0 ; y-- ) {
            Kostka kst = list.get(y -1); 
        }}

when I try to compile this code, it says that the (y -1) (3rd line) is incompatible

Upvotes: 1

Views: 915

Answers (5)

cl-r
cl-r

Reputation: 1264

Tip for enhancement : put the -1a the beginning of the loop, so you avoid list.size() substractions in the loop. If possible, keep Koska ksk final.

for (int y = list.size() - 1; y > 0; y--) {
    final Kostka kst = list.get(y);
}

Upvotes: 0

sanbhat
sanbhat

Reputation: 17622

First I suggest you to use generics for ArrayList.

like

   void testK(ArrayList<Kostka> list) {
    for (int y= list.size() ; y > 0 ; y-- ) {
        Kostka kst = list.get(y -1); 
    }}

or you need to cast the object got from list to your type Kostka

void testK(ArrayList list) {
        for (int y= list.size() ; y > 0 ; y-- ) {
            Kostka kst = (Kostka)list.get(y -1); 
        }}

Upvotes: 1

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

In the way you have written your code, the get(y - 1) will return an Object instance.

You have to cast it:

Kostka kst = (Kostka) list.get(y -1); 

Also, avoid using raw types like ArrayList. Instead, use Generic collections (ArrayList<Kostka>)

Upvotes: 1

Uwe Plonus
Uwe Plonus

Reputation: 9954

You either have to cast the result of list.get() to your type

Kostka kst = (Kostka)list.get(y -1);

or work with generics and supply a generic list to your method

void testK(ArrayList<Kostka> list)

Upvotes: 7

Reimeus
Reimeus

Reputation: 159784

You're using a raw type for the ArrayList passed in, therefore you need to cast

Kostka kst = (Kostka) list.get(y -1); 

but better to use generics to avoid casting

ArrayList<Kostka> list

Upvotes: 9

Related Questions