Shivam Pandey
Shivam Pandey

Reputation: 86

how to remove element from LinkedList<Integer> array[]

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

Upvotes: 0

Views: 136

Answers (2)

Djaouad
Djaouad

Reputation: 22776

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]

Upvotes: 1

bcr666
bcr666

Reputation: 2197

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);

Upvotes: 1

Related Questions