I just recently started learning Java and wanted to try creating a list of lists. In all the examples I've come across on the internet, inorder to add lists of integers as different elements to another list,different lists were created.
When tried using a single list but with changing it's values each time before adding them ((as shown in the code below), I am getting the following result. I tried doing another similar code, but this time with just a single list of objects. And in that case also, I am getting a similar result.
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]
*/
}
}
Does this mean that when dealing with objects as elements of list, it references them? And also, is there any way of making the code work with the same object/list to give the desirable outputs as follows?
[[1, 3, 5], [30, 65, 56]]
[ID: 2 , Name: Amy, ID: 4 , Name: Jake]
Looks like you want to have a List with two different elements, yet create only one in each case.
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);
What you might want to do is replacing object modification p1.set(4, "Jake")
with object creation p1 = new Person(4, "Jake")
, and then you will be good to go.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments