1
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

  • but the list.size() method should return an integer, so whats the problem ?
4
  • 1
    please post the full stack trace. Commented Jun 13, 2013 at 13:01
  • 3
    Of what type is your ArrayList ? It Should be ArrayList<Kostka> list Commented Jun 13, 2013 at 13:02
  • @Doorknob he is saying compiler error Commented Jun 13, 2013 at 13:02
  • okay, then please post the full error. Commented Jun 13, 2013 at 13:02

5 Answers 5

9

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
Sign up to request clarification or add additional context in comments.

Comments

7

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)

Comments

1

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>)

Comments

1

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); 
        }}

Comments

0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.