【问题标题】:Adding to LinkedList changes initial value添加到 LinkedList 会更改初始值
【发布时间】:2016-12-07 06:08:48
【问题描述】:

这段代码应该迭代一个 LinkedList,其中包含一系列包含最多 9 个数字的列表。关键是将一个数字更改为其负数,然后将更改了一个数字的列表添加回包含以下内容的 LinkedList所有排列。例如:对于集合1 2 3,排列到8,从[1 2 3]开始,第一次迭代后应该包含[[1 2 3] ,[-1 2 3]]的列表,第二次迭代应该包含[[1 2 3], [- 1 2 3], [1 -2 3], [-1 -2 -3]]的链表,等等。 Linked list的结束长度应该是2^n,这对于最终输出来说是正确的,但是实际数据是完全错误的。

问题:输出仅将列表的第一个数字显示为负数,因此对于上面的示例,仅(-1 2 3) 打印了 8 次。这让我很困惑,因为链接列表中的第一个 List<Integer> 是 (1 2 3)。这个程序如何改变我列表中的初始对象,为什么它不断添加一个只改变了第一个整数的列表?谢谢,

//Will make neg for one place in each list in linked list, adding changed 
//list back to linkedlist
public void makeNeg(Integer place){
    Integer target = 0;
    List<Integer> hold = new ArrayList<Integer>();

    //list is a class variable
    Iterator<List<Integer>> it = list.iterator();
    while(it.hasNext()){
        hold = it.next();
        target = hold.get(place);
        target *= -1;
        hold.set(place, target);
        list.addLast(hold);
    }
}

//Should run program
public void run(Integer place){
    if(!(number > place)){
        System.out.print("---Completed Successfully ---\n");
    }else{
        makeNeg(place);
        run(place+1);
    }
}

Output for Integer of 3
-1 +2 +3 
-1 +2 +3 
-1 +2 +3 
-1 +2 +3 
-1 +2 +3 
-1 +2 +3 
-1 +2 +3 
-1 +2 +3 

【问题讨论】:

  • 你只有一个列表 hold 并内联改变这个列表,重复添加对它的引用到你的 token 列表中。您需要复制您的hold 列表。
  • 什么是list,当您立即用hold = it.next() 语句替换该列表时,为什么要将hold 初始化为新的ArrayList?另外,您是否误以为token.addLast(hold) 会添加hold副本
  • ... 我可能会误以为 token.addLast(hold) 会添加一个 hold 的副本。它只添加地址不是吗,而不是添加副本

标签: java list linked-list iterator integer


【解决方案1】:

我找到了一种方法来使用此链接 (http://javatechniques.com/blog/faster-deep-copies-of-java-objects/) 中的一些代码来回答这个问题。我创建了一个实现可序列化的对象,并使用了在我链接的 url 中找到的这段代码。

public static numbers copy(numbers orig) {
    numbers obj = null;
    try {
        // Write the object out to a byte array
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bos);
        out.writeObject(orig);
        out.flush();
        out.close();

        // Make an input stream from the byte array and read
        // a copy of the object back in.
        ObjectInputStream in = new ObjectInputStream(
            new ByteArrayInputStream(bos.toByteArray()));
        obj = (numbers)in.readObject();
    }
    catch(IOException e) {
        e.printStackTrace();
    }
    catch(ClassNotFoundException cnfe) {
        cnfe.printStackTrace();
    }
    return obj;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 2012-12-29
    相关资源
    最近更新 更多