The following code has compilation issues. The compilation error is also attached. Please suggest solution to the same.
Code:
import java.util.*;
class test{
int key;
public static void main(String []args){
test obj = new test();
obj.key = 9999;
LinkedList al = new LinkedList();
al.add(obj);
Iterator itr = al.iterator();
while(itr.hasNext()){
test temp = new test();
temp = itr.next();
System.out.println(temp.key);
}
}
}
Compilation Error :
test.java:17: error: incompatible types
temp = itr.next();
^required: test
found: Object
its.next()returns an instance ofObjectand not theTestMake it as follows
So compiler now knows that
LinkedLista1can only holdTestinstances so while iterating we will only have instances ofTest