I had two classes: ParentClass and SubClass. SubClass inherit from ParentClass.
I had the following code: (inside class)
List<SubClass> lstSub;
//some initialization
public ListIterator getLstIterator(int i) {
return lstSub.listIterator(i);
}
And client class uses it the following way:
ListIterator<ParentClass> lstParent = getLstIterator(0); //assign ListIterators
So, the question:
What does the program do while assigning ListIterators:
1) it creates a new list and copies there elements from source list, casting them to ParentClass;
2) it simply creates a link to lstSub and from this time this list is interpreted as List for ListIterator?
Or it does something else?
I’m interested in it because of program performance. I’m new to Java and appreciate any help.
It doesn’t create another list. If you get a list iterator without knowing the class in the list, that’s going to be an error in your generics usage. You should get a warning when you do that assignment, but it’s just a warning. When you actually use it it’ll cast to whatever class. Properly you’d hold on to that as
ListIterator<? extends ParentClass>if you wanted a list iterator, but actually holding on to an iterator is a little weird.Finally, just a bit of advice, I’d not worry about performance of the language features too much, especially if you’re just getting your feet in the language.