简体   繁体   English

添加到ArrayList对象的ListIterator

[英]Adding to a ListIterator of an ArrayList Object

I'm writing a program that manipulates an ArrayList with ListIterator without using any ArrayList methods. 我正在编写一个程序,使用ListIterator操作ArrayList而不使用任何ArrayList方法。 The ArrayList in this case is supposed to behave like a set. 在这种情况下,ArrayList应该表现得像一个集合。

My add method traverses the ArrayList and compares each element with the number to be added so that repeats can be avoided. 我的add方法遍历ArrayList并将每个元素与要添加的数字进行比较,以便可以避免重复。 OurSet() is the constructor of the class. OurSet()是类的构造函数。 I also redefine the toString method to print using ListIterator methods. 我还重新定义了toString方法以使用ListIterator方法进行打印。

When I tested these two methods, it appeared that the add method didn't actually added anything (or the print statement isn't showing it). 当我测试这两种方法时,似乎add方法实际上没有添加任何东西(或者print语句没有显示它)。 The output using the main method below is blank, and I'm not quite sure why. 使用下面主要方法的输出是空白的,我不太清楚为什么。 I traced through the code a few times, and placed print statements in the methods to make sure that they did run through every line. 我对代码进行了几次跟踪,并在方法中放置了print语句,以确保它们确实贯穿了每一行。 In the toString method, it never enters the while loop. 在toString方法中,它永远不会进入while循环。 The code is below, and any help is appreciated! 代码如下,任何帮助表示赞赏!

OurSet()
{
//      list is the ArrayList object, it was defined earlier and now instantiated
    list = new ArrayList();
//      iter is the ListIterator object, it was defined earlier and now instantiated
    iter = list.listIterator();
}

public void add(int x)
{
    while(iter.hasNext())
    {
        int item = (Integer) iter.next();
        if(item == x)
            break;
    }
    iter.add(new Integer(x));
}

public String toString()
{
    String set = "";
    while(iter.hasNext())
    {
        int item = (Integer) iter.next();
        set += item + " ";
    }
    return set;
}

Here is my main method. 这是我的主要方法。

public static void main(String args[])
{
    OurSet set = new OurSet();
    set.add(50);
    System.out.println(set);
}

Instantiating an IteratorList object will cause it to start back from the beginning. 实例化IteratorList对象将使其从头开始。 Since the only time I instantiated the object was in the constructor, it had already reached the end of the list in the add method and the toString method couldn't loop through it again. 由于我实例化对象的唯一时间是在构造函数中,因此它已经在add方法中到达列表的末尾,而toString方法无法再次遍历它。 By re instantiating iter in toString method, the list was printed out properly. 通过在toString方法中重新实例化iter ,列表被正确打印出来。

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

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