我最近刚开始学习Java,想尝试创建一个列表列表。在我在互联网上遇到的所有例子中,为了将整数列表作为不同的元素添加到另一个列表中,创建了不同的列表。
当尝试使用单个列表,但每次添加之前都要更改其值(如下面的代码所示(时,我得到了以下结果。我尝试了另一个类似的代码,但这次只使用了一个对象列表。在这种情况下,我也得到了类似的结果。
class Persona
{
int num;
String name;
public String toString()
{ return("ID: "+num+" , Name: "+name); }
public Persona(int num, String name) {
this.num = num;
this.name = name; }
public void set(int num,String name) {
this.num = num;
this.name = name;
}
}
public class Trials {
public static void main(String[] args) {
//CASE 1 : TRYING WITH A LIST OF LISTS
List< List< Integer> > collection = new LinkedList<>();
List<Integer> triplet = new LinkedList<>();
triplet.add(1);
triplet.add(3);
triplet.add(5);
collection.add(triplet);
System.out.println(collection);
triplet.clear();
triplet.add(30);
triplet.add(65);
triplet.add(56);
collection.add(triplet);
System.out.println(collection);
//CASE 2 : TRYING WITH LIST OF OBJECTS
Persona p1 = new Persona(2,"Amy");
List< Persona > people = new LinkedList<>();
people.add(p1);
System.out.println(people);
p1.set(4, "Jake");
people.add(p1);
System.out.println(people);
/*OUTPUT:-
[[1, 3, 5]]
[[30, 65, 56], [30, 65, 56]]
[ID: 2 , Name: Amy]
[ID: 4 , Name: Jake, ID: 4 , Name: Jake]
*/
}
}
这是否意味着当将对象作为列表的元素处理时,它会引用它们?此外,是否有任何方法可以使代码与相同的对象/列表一起工作,以提供如下所需的输出?
[[1, 3, 5], [30, 65, 56]]
[ID: 2 , Name: Amy, ID: 4 , Name: Jake]
看起来您想要一个包含两个不同元素的List,但在每种情况下只创建一个。
List< Persona > people = new LinkedList<>();
// Create p1 (Amy)
Persona p1 = new Persona(2, "Amy");
// Add p1 (Amy) to people, now people is [p1 (Amy)]
people.add(p1);
// [p1 (Amy)]
System.out.println(people);
// Set p1's name to Jake, it also updates in the list because it is the same object
// so now people is [p1 (Jake)]
p1.set(4, "Jake");
// Add p1 to list one more time, now people is [p1 (Jake), p1 (Jake)]
people.add(p1);
// [p1 (Jake), p1 (Jake)]
System.out.println(people);
您可能想要做的是用对象创建p1 = new Person(4, "Jake")
替换对象修改p1.set(4, "Jake")
,然后就可以开始了。