【问题标题】:Java unmodifiable arraylist programming testJava不可修改的arraylist编程测试
【发布时间】:2025-11-22 01:25:03
【问题描述】:

请在投票前阅读 cmets。

以下是给定的代码;当前输出[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]
    }
}

应该采用什么方法?

注意:测试已经结束,请您回答问题,谢谢!

【问题讨论】:

  • 至少你应该展示你的方法。这个社区不是为了解决你不能解决的问题,而是为了帮助你解决问题。并且没有提供您的解决方案,或者至少没有提供您的方法。
  • 不知道问题出在哪里。list.set(0, 3); 设置索引 0 == 3 您正在将值从 1 更改为 3,因此预期的输出 3,2 是正确的
  • @Luminous_Dev 是的,所以你必须修改 restore() 方法,使输出为 1,2。
  • 对不起,为什么要修改这个?

标签: java arrays arraylist


【解决方案1】:

你的问题有点不具体。 但我认为 restore 应该恢复初始输入。

因此:

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;
}

【讨论】:

  • 仍然会输出 1,2 和 1,2,4
  • 但这是。我没有正确阅读您的主要内容,您正在获取对 init 的引用并对其进行修改,这导致了问题,但现在没有了。
【解决方案2】:

您需要在代码中进行一些更改。问题是Java 通过reference 操作Objects,并且您执行了一些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.
}

【讨论】:

  • 完美。谢谢
最近更新 更多