【发布时间】:2020-09-24 16:13:34
【问题描述】:
我最近刚开始学习 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]
【问题讨论】:
-
请注意,在 Java 中使用多属性
set方法不是惯例。相反,您将分别拥有setName和setId。
标签: java list linked-list