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();
}
}
}
Yes – you’re not using generics anywhere, so
i.next();is just returningObjectas far as the compiler is concerned.Options:
Cast to
Square:Personally I’d favour using generics – it’s much nicer to have type safety where you can 🙂
Two asides:
The enhanced
forloop can replace your while loop:It’s odd to have an instance method called
mainwith no parameters; it’s more common to havepublic static void main(String[] args). There’s nothing illegal about what you’ve done here, just odd.