如何使它成为一个arraylist中的数据一旦被添加就不可更改

时间:2017-03-04 07:02:32

标签: java arraylist

我有一个2类,一个类Human,它是一个简单的对象,包含一个名字的字符串和一个年龄的int。我的另一个类有两个参数,它们自己的名字和一个Human类型的数组。

public class Human {

private String name;
private int age;


public Human (String currName, int currAge) 
{

    name = currName;
    age = currAge;

}

public String getName() 
{
    return name;
}

public int getAge() 
{
    return age;
}

public void setName(String newName) 
{
    name = newName;
}

public void setAge (int newAge) 
{
    age = newAge;
}

}

import java.util.*;


public class AListCopyTest {

private String name;
private ArrayList<Human> HumanList = new ArrayList<>();


public AListCopyTest(String currName, ArrayList<Human> HList) 
{
    name = currName;
    HumanList = HList;
}

public String getName(){
    return name;
}

public ArrayList<Human> getListofHumans(){
    return HumanList;
}

public void setName(String newName) {
    name = newName;
}

public void setListofHumans(ArrayList<Human> newList){
    HumanList = newList;
}





/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here

    System.out.println("Testing Array Creation");

    Human One = new Human("John", 10);
    Human Two = new Human("Mary", 20);
    Human Three = new Human("Steve", 30);
    Human Four = new Human("Paul", 55);

    ArrayList<Human> MainList = new ArrayList<>();

    MainList.add(One);
    MainList.add(Two);
    MainList.add(Three);
    MainList.add(Four);

    AListCopyTest Trial1 = new AListCopyTest("List of Humans", MainList);

    //System.out.println(Trial1);
    for (Human count: MainList) 
    {
        System.out.println("Person Name: " + count.getName() + "    Person Age: " + count.getAge());
    }


    System.out.println("\n" + "\n");
    //Now need to make it so ArrayList is unaffected by what comes next
    //Effectively need to make it so the print happens after the changes are made, yet prints info from before changes
    One.setName("Peter");
    Two.setAge(33);
    Three.setAge(50);
    Three.setName("Carlos");
    Four.setName("Jane");

    for (Human count: MainList) 
    {
        System.out.println("Person Name: " + count.getName() + "    Person Age: " + count.getAge());
    }



}

}

我试图做的就是让人类被添加到数组中时,它会被有效地锁定在&#34;它具有生命周期的参数,因此我的任何设置器都无法对其进行更改,因此当它再次打印时,输出与第一次运行时的输出相同。

我知道我可以让一个复制构造函数在我做任何更改之前创建一个副本,然后只是打印出来,但那不是我需要的。我需要它,以便我可以从完全相同的arraylist打印并获得相同的结果。我怎么会这样做呢?我已经阅读了关于使List无法变换的内容,但我仍然希望能够在需要时添加到列表中,只是无法更改已经存在的内容。

如果需要,这就是我的输出目前的样子:

Testing Array Creation
Person Name: John    Person Age: 10
Person Name: Mary    Person Age: 20
Person Name: Steve    Person Age: 30
Person Name: Paul    Person Age: 55



Person Name: Peter    Person Age: 10
Person Name: Mary    Person Age: 33
Person Name: Carlos    Person Age: 50
Person Name: Jane    Person Age: 55

1 个答案:

答案 0 :(得分:0)

您需要做的就是不创建setter,只需创建一个无法创建arraylist的构造函数。另外,创建一个addItem方法,将项添加到arraylist而不是添加setter。