I use Java.
I already have a class for a custom object called "Subject".
I have another class that only contains a Linked List of Subject objects. (called subjectsList)
I wrote one of the methods (called "getSubject()") in the subjectsList class that is meant to return the Subject object at a specific index in the Linked List. To do this, I used a ListIterator. I would create a ListIterator at a given index in the LinkedList and use the .next() method.
However, the .next() method in a ListIterator only returns a java.lang.Object, even though I want it to return a Subject object.
How do I get ListIterator.next() to return a Subject object?
I've tried downcasting to a Subject but this seems to fail, and I read somewhere that you can't downcast unrelated objects.
This is my subjectsList class:
import java.util.*;
public class subjectsList
{
//my LinkedList of Subject objects and a ListIterator
private LinkedList<Subject> l;
private ListIterator itr;
//constructor that simply creates a new empty LinkedList
public subjectsList()
{
l = new LinkedList();
}
//Method to return the Subject object at a specific index in the LinkedList
public Subject getSubject( byte index )
{
itr = l.listIterator( index );
return itr.next();
}
//Method to add a new Subject object to the LinkedList
public void addSubject( String nameInput, byte levelInput )
{
l.addLast( new Subject( nameInput, levelInput ) );
}
//Method to remove the Subject object at a specific index in the LinkedList
public void removeSubject( byte index )
{
itr = l.listIterator( index );
itr.next();
itr.remove();
}
}
The method in question is the "getSubject()" method.