简体   繁体   English

在Java中将迭代器与链表一起使用

[英]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. 我创建了一个名为“ SList”的链接列表类,该类允许创建一个空的链接列表。 The method "insertFront" inserts an object at the front of the list and increases the size. 方法“ insertFront”将对象插入列表的前面并增加大小。 Below, in the main class, I have created an SList object and added two strings to the list. 在下面的主类中,我创建了一个SList对象,并将两个字符串添加到列表中。 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". 我试图创建一个从java.util导入的迭代器对象,但是编译器在“ 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. 给定您当前的实现,没有方法可以从SList类返回Iterator对象。

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: 如果您希望基于Java Collections框架实现您的实现,则应在代码中实现Collection接口,如下所示:

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

The <E> is a parameterized type that makes your class type-safe. <E>是使您的类类型安全的参数化类型。 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> . 如果实现Collection接口,则将需要实现几种方法,其中一个方法将返回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. 如果您选择不使用Java Collections框架,那么这样做就很容易,您只需创建自己的所有方法即可。

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 可以在Java教程页面上找到有关泛型的出色教程(如果您不想使用Collections框架)

Another great tutorial for the Collections framework can also be found here at the Java Tutorials page for Collections 在此处的Collections的Java Tutorials页面上,也可以找到Collections框架的另一篇很棒的教程。

Have fun! 玩得开心!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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