2017-04-23 41 views
-5

请在downvoting之前阅读注释。Java不可修改的数组编程测试

以下是给定的代码;目前输出[3,2][3,2,4]。您必须修改restore()方法,以便输出将是[1,2][1,2]

import java.util.ArrayList; 

public class Solution { 
    private ArrayList<Integer> data; 

    public Solution(ArrayList<Integer> data) { 
     this.data = data; 
    } 

    public ArrayList<Integer> restore() { 
     return this.data; 
    } 

    public static void main(String[] args) { 
     ArrayList<Integer> list = new ArrayList<Integer>(); 
     list.add(1); 
     list.add(2); 
     Solution snap = new Solution(list); 
     list.set(0, 3); 
     list = snap.restore(); 
     System.out.println(list); // Should output [1, 2] 
     list.add(4); 
     list = snap.restore(); 
     System.out.println(list); // Should output [1, 2] 
    } 
} 

应该怎么办?

注:测试已完成,因此您可以回答问题,谢谢!

+0

至少你应该表现出你的方法。这个社区不是为了解决你不能解决的问题,而是为了解决你的问题。并没有提供您的解决方案或至少您的方法。 – sascha10000

+0

不知道什么问题在这里..'list.set(0,3);'设置索引0 == 3你正在改变一个值从1到3所以期望输出3,2是正确的 –

+0

@Luminous_Dev是的,所以你必须修改restore()方法,以便输出为1,2。 – Amit1011

回答

1

你的问题是一种非混凝土。 但我认为还原应该恢复初始输入。

因此:

ArrayList<Integer> init; 
public Solution(ArrayList<Integer> data) { 
    this.data = data; 
    this.init = new ArrayList<Integer>(data); 
}  

public ArrayList<Integer> restore() { 
    ArrayList<Integer> cpy = new ArrayList<Integer>(this.init); 
    return cpy; 
} 
+0

它仍然会输出1,2和1,2,4 – Amit1011

+0

这将起作用。 – sascha10000

+0

仍然没有工作.. – Amit1011

1

这里需要做出一些改变的代码。问题是Java操纵Objectsreference,并且您执行了一些manipulation operations,因为reference而更改了原始数据。

你的代码改成这样:

public Main(ArrayList<Integer> data) 
{ 
    ArrayList<Integer> newList = new ArrayList<Integer>();  

    for(Integer in:data) 
     newList.add(in); 

    this.data = newList; 
} 

public ArrayList<Integer> restore() 
{ 
    ArrayList<Integer> newList = new ArrayList<Integer>(); 

    for(Integer in:data) 
     newList.add(in); 

    return newList; //returns a reference of a list which has nothing to do with the original list. 
} 
+0

完美。谢谢 – Amit1011