添加到LinkedList会更改初始值

时间:2016-12-07 06:08:49

标签: java list linked-list iterator integer

这段代码应该迭代一个包含Lists的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]],等等。 链接列表的结束长度应为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 

1 个答案:

答案 0 :(得分:0)

通过使用此链接中的一些代码(http://javatechniques.com/blog/faster-deep-copies-of-java-objects/),我找到了回答此问题的方法。我创建了一个实现serializable的对象,并使用了我链接的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;
}