Sysel
Sysel

Reputation: 41

Java ArrayList incompatible types

i have a problem . I'm trying to add and them retrieve objects of the same class to ArrayList , but when i try to retrieve them i get incompatible types erroe

import java.util.*;

public class Test{

Test(){
    main();
}

List test = new ArrayList();

public void main(){
    test.add(new Square(10));

    Iterator i = test.iterator();
    while(i.hasNext()){
        Square temp = i.next();
    }
}
}

Upvotes: 1

Views: 4872

Answers (3)

Andreas Dolk
Andreas Dolk

Reputation: 114777

You have to cast to Square:

while(i.hasNext()){
    Square temp = (Square) i.next();
}

The iterator will return Object type elements only.

With Java 1.5+ and generics, we can do it without casting:

// a list, that will only accept Square instances
List<Square> test = new ArrayList<Square>();

public void main(){
    test.add(new Square(10));

    Iterator<Square> i = test.iterator();
    while(i.hasNext()){
        Square temp = i.next();
    }
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500625

Yes - you're not using generics anywhere, so i.next(); is just returning Object as far as the compiler is concerned.

Options:

  • Use generics
  • Cast to Square:

    Square temp = (Square) i.next();
    

Personally I'd favour using generics - it's much nicer to have type safety where you can :)

// Not clear why this is an instance variable - and please make fields private :)
List<Square> test = new ArrayList<Square>();

public void main() {
    test.add(new Square(10));

    Iterator<Square> i = test.iterator();
    while(i.hasNext()) {
        Square temp = i.next();
        // Use square here
    }
}

Two asides:

  • The enhanced for loop can replace your while loop:

    for (Square square : test)
    
  • It's odd to have an instance method called main with no parameters; it's more common to have public static void main(String[] args). There's nothing illegal about what you've done here, just odd.

Upvotes: 6

amit
amit

Reputation: 178451

You should use the generic type List<Square>, ArrayList<Square> and Iterator<Square> to avoid this.

If you don't the compiler cannot "know" what is the actual types of elements in test, and it "thinks" them as of type Object.

List<Square> test = new ArrayList<Square>();
public void main(){
    test.add(new Square(10));

    Iterator<Square> i = test.iterator();
    while(i.hasNext()){
        Square temp = i.next();
    }
}

Upvotes: 1

Related Questions