I have an home work,I used an array and element of array is linked list because the element in a row is not fixed need delete or add some time depend on problem condition , I was tried these codes below, but I have a problem when adding new element to a fixed row for example p[0] the value will be added for all, how I can solve this problem please help.
public class schedule
{
public class link
{
public LinkedList <Integer>list = new LinkedList<Integer>() ;
public link(LinkedList<Integer> value)
{
list = value;
}
public link(int value)
{
list.add(Integer.valueOf(value)) ;
}
}
private link p[] = new link[10];
public schedule()
{
LinkedList<Integer> l = new LinkedList<Integer>();
l.add(Integer.valueOf(2));
l.add(Integer.valueOf(0));
l.add(Integer.valueOf(3));
for(int j=0;j<p.length;j++)
p[j] = new link(l);
p[0].list.add(9); // here I have problem
for(int j=0;j<p.length;j++)
{
System.out.print("p["+j+"]:");
for(int i=0;i<p[j].list.size();i++)
System.out.print(p[j].list.get(i).intValue());
System.out.println();
}
}
public static void main(String []arg)
{
new schedule();
}
the output is like this : the value 9 added to all but I want to be added just for first element
p[0]:2039
p[1]:2039
p[2]:2039
p[3]:2039
p[4]:2039
p[5]:2039
p[6]:2039
p[7]:2039
p[8]:2039
p[9]:2039
The problem is that you’re initializing every
linkinstance with the sameLinkedList<Integer>:Take note that when you do this, every
linkinstance will have thelistattribute referencing the sameLinkedList<Integer> lvariable. So, if you modify it in one place, everyone will be updated (because it’s the same reference).There are many ways to solve this:
linkinstance using another constructor.link[] parray one by one…