Error: cannot resolve symbol
This error occurs in the following code:
public class example {
public static void main(String[] args) {
ArrayList list = new ArrayList();
for (int i = 0; i < 4; i++)
{
list.add (new Integer (i*i));
System.out.println (list.get(i));
}
}
}
Does anyone have any suggestions how to print the elements in the arraylist? The error I get is
"cannot resolve symbol class ArrayList"
TIA
Re: Error: cannot resolve symbol
Try adding in an import directive. import java.util.*;
Re: Error: cannot resolve symbol
This code uses java 5's(jdk1.5.0) new feature called generics. They are supposed to increase type safety by only allowing the <type> or it's subtypes to be stored within the Collection. Also casting should not be needed when grabbing an element out of a collection to be stored in ref variable of the <type>. But for some reason a cast is still needed ie. Integer integer = (Integer)i.next(); even though the Collection is specified only to hold <Integer> types. If <type> is added to the Iterator then the cast is not needed.
Code:
for(Iterator<Integer> i = list.iterator();i.hasNext();){
Integer integer = i.next(); then the cast is not needed.
}
Code:
import java.util.*;
List<Integer> list = new ArrayList<Integer>();
int element = 0;
while(true){
list.add(new Integer(element));
element = element + 1; // add 4 elements
if(element == 4) break;
}
for(Iterator i = list.iterator();i.hasNext();){
Integer integer = (Integer)i.next();
System.out.println(integer);
}
Re: Error: cannot resolve symbol
Quote:
But for some reason a cast is still needed ie. Integer integer = (Integer)i.next(); even though the Collection is specified only to hold <Integer> types.
The Iterator doesn't know where it came from. That's the weird thing about Java's generics. If the iterator itself doesn't have the type specified, then it's just a normal iterator over Objects.
Re: Error: cannot resolve symbol
Quote:
Posted by CornedBee
The Iterator doesn't know where it came from. That's the weird thing about Java's generics. If the iterator itself doesn't have the type specified, then it's just a normal iterator over Objects.
Yeah it's kinda odd how the language dosen't force the deveopler to specify a type when declaring an Iterator, but then again i guess it's not needed. I don't really see any added benefit of type saftey by having to do that.
Re: Error: cannot resolve symbol
The problem is that the system cannot determine what type it's supposed to be. An Iterator is just an Iterator. An Iterator<Byte> is what does the type checking.