0
LinkedList<INteger> ar[4];

for(int i=0;i<4;i++)
{
    ar[i]=new LinkedList();
}

ar[0].add(99);
ar[1].add(60);
ar[0].add(66);
ar[0].add(61);

// how to remove 66 from List 0 index
ar[0].remove(66);
//but this above statement shows error
krokodilko
  • 35,300
  • 7
  • 55
  • 79
Shivam Pandey
  • 86
  • 2
  • 8

2 Answers2

1

Java thinks the 66 you are passing in to the method ar[0].remove(66); is an index, not the object, so you need to get the index of the object first.

int index = ar[0].indexOf(66);
ar[0].remove(index);
bcr666
  • 2,157
  • 1
  • 12
  • 23
  • Well I have one more question when passing linked list in functions java passes it by call by reference right how to pass it without reference – Shivam Pandey Mar 19 '18 at 21:31
  • Java always passes by value, not reference. https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – bcr666 Mar 19 '18 at 21:43
  • see this https://stackoverflow.com/questions/29617827/when-i-use-linkedlist-in-java-it-seems-not-to-pass-by-value-anymore-anyone-c – Shivam Pandey Mar 19 '18 at 21:49
  • So to clarify, when you pass an object variable into a method, you are passing in a pointer to the object. Inside the method, the variable in the method signature has a copy of the pointer, not the object, so when you mutate a property of the object, it is seen outside of the method. If this is not what you want, you need to clone your object. – bcr666 Mar 19 '18 at 21:49
  • even the cloning is also not working for LinkedList i dont know why – Shivam Pandey Mar 19 '18 at 21:50
  • If this question is answered, then you should mark it so, and start a new question if you are having another problem. – bcr666 Mar 19 '18 at 21:52
1

There can be two types passed as an argument to LinkedList#remove:

  1. an int (which is considered the index of the element to be removed).
  2. an Integer (which is considered the value of the element to be removed).


// remove 66 by index
int index = ar[0].indexOf(66);
if (index > -1) // if it exists
   ar[0].remove(index);
System.out.println(ar[0]); // => [99, 61]

// remove 66 by value
ar[0].remove(new Integer(66));
System.out.println(ar[0]); // => [99, 61]
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55