简体   繁体   中英

Using an iterator with a linked list in Java

I have created a linked-list class called "SList", which allows an empty linked-list to be created. The method "insertFront" inserts an object at the front of the list and increases the size. Below, in the main class, I have created an SList object and added two strings to the list. I would like to print this list. I attempted to create an iterator object imported from java.util, but the compiler is giving me a red underline under "Iterator". Why am I getting this error? How should I print this linked-list?

public class SList 
{
private SListNode head;
private int size; //number of items in the list

public SList() //constructor, empty list
{
    head = null;
    size = 0;
}
public void insertFront(Object item)
{
    head = new SListNode(item, head);
    size++;
}

}

import java.util.*;

public class LinkMain 
  {
        public static void main(String[] args)
    {
    String apples = "apples";
    String oranges = "oranges";

    SList x = new SList();

    x.insertFront(apples);
    x.insertFront(oranges);

    Iterator iter = x.Iterator();






}

}

I'm a bit confused by your code. Given your current implementation, there is no method that will return an Iterator object from your SList class.

If you would like to base your implementation off of the Java Collections framework, you should implement the Collection interface in your code as such:

public class SList<E> implements Collection<E> {
    //override methods here
}

The <E> is a parameterized type that makes your class type-safe. If you implement the Collection interface, you will be required to implement several methods, among them is a method that will return an Iterator<E> .

If you choose not to use the Java Collections framework, it is just as easy to do, you'll just need to create all of your own methods.

A great tutorial for generics (if you don't want to use the Collections framework) can be found here at the Java Tutorials page for generics

Another great tutorial for the Collections framework can also be found here at the Java Tutorials page for Collections

Have fun!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM