Get a Java list iterator to return something other than Object

I am using Java.

I already have a class for a custom object called "Theme."

I have another class that contains only a Linked List of Subjects. (called subjectList)

I wrote one of the methods (called "getSubject ()") in the objectsList class, which is designed to return a Subject at a specific index in a Linked List. For this, I used ListIterator. I would create a ListIterator at the given index in LinkedList and use the .next () method.

However, the .next () method in the ListIterator returns a java.lang.Object, although I want it to return a Subject.

How to get ListIterator.next () to return a Subject?

I tried to suppress the topic, but that seems to be failing, and I read somewhere that you cannot dump unrelated objects.

This is my subjectList 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();
    }
}

This method is the getSubject () method.

+5
source share
2 answers

You need to declare your iterator as:

private ListIterator<Subject> itr;

Also create a LinkedList object as follows in the constructor:

l = new LinkedList<Subject>();

You can also pass it to the Subject by returning it, since your list saves the Subject. But it would be better to define an Iterator, as mentioned earlier.

public Subject getSubject( byte index )
{
    itr = l.listIterator( index );
    return (Subject)itr.next();
}

Besides your problem, I see a naming problem in the code. Better to follow him and make a habit.

. , Eclipse IDE. IDE, .

+5

ListIterator.

private ListIterator<Subject> itr;

itr.next() .

:

PS: LinkedList l = new LinkedList<Subject>();

+4

All Articles