Type mismatch returning item from LinkedList

I have an object of class A:

public class A
{
    private int num;
    private char color;
}

That I'm trying to read into an Array from a LinkedList using the Iterator, like so:

public static void main()
{
    LinkedList<A> A = new LinkedList<A>();

    //make some objects of class A

    A.add(A1);
    A.add(A2);
    A.add(A3);

    Iterator it = A.iterator();

    A[] arrayA = new A[3];

    for (int i = 0; i < 3; i++) 
        {
           > arrayA[i] = it.next();
        }
}

The line marked with a > in the code above gives me the following compiler error: Type mismatch: cannot convert from Object to A

I looked this up and thought I was safe from the issue of raw types by instantiating LinkedList to be of type A and that LinkedList would be returning an A, not an Object, but it's still giving me the same compiler error. Why is that?

4 answers

  • answered 2017-06-17 18:17 Andrii Abramov

    You have to specify generics of Iterator:

    Iterator<T> it = A.iterator();
    

    Because you have not specified it explicitly, iterator it stores raw types (Object).

    If you don't want to specify genetics (but I definitely recommend to do it) you have to explicitly cast value returned from it.next():

    Iterator it = A.iterator();
    
    
    for (int i = 0; i < 3; i++) {
        arrayA[i] = (A) it.next();
    }
    

  • answered 2017-06-17 18:17 Ryan Dale

    Try to cast it.next() to A. arrayA[i] = (A) it.next();

  • answered 2017-06-17 18:17 Ravi

    Because, it.next(); returns Object instance as you haven't specified type at below line

     Iterator it = A.iterator();
    

    You need to specify generics to return instance of A.

     Iterator<A> it = A.iterator();
    

  • answered 2017-06-17 18:17 Joy Dir

    Because you don't specify type of iterator, your iterator is raw typed, correct code here:

    public static void main() {
        LinkedList<A> A = new LinkedList<A>();
    
        A.add(new A());
        A.add(new A());
        A.add(new A());
    
        Iterator<A> it = A.iterator();
    
        A[] arrayA = new A[3];
    
        for (int i = 0; i < 3; i++) {
             arrayA[i] = it.next();
        }
    }