Thursday, March 12, 2009

Assume you have an ArrayList with 7 objects in it. And there is an int[] as

Question :Assume you have an ArrayList with 7 objects in it. And there is an int[] as
int[] intArray = new int[3];
intArray[0] = 2;
intArray[1] = 4;
intArray[2] = 6;
How do you go about deleting objects from ArrayList based on the values
present in int[]? (CoreJava)

Answer :This looks to be very simple question as we can make a for loop and
remove objects from
ArrayList. But remember that for the first time when you try to remove an
object at index 2 from ArrayList,
you would end up with an ArrayList size reduced from 7 to 6.
And your code would be throwing ArrayIndexOutOfBoundsException. Have
a look at this piece of code
public void testArrayList()
{
int[] intArray = new int[3];
intArray[0] = 2;
intArray[1] = 4;
intArray[2] = 6;
ArrayList al = new ArrayList();
for(int i=0; i < 7; i++)
{
al.add("test "+i);
}
System.out.println(al);
for(int x=0; x < intArray.length; x++)
{
System.out.println(al.remove(intArray[x]));
}
}
The above code doesn't work as the ArrayList size would shrink when you
try to remove the first element.
Have a look at this working code below
public void testArrayList()
{
int[] intArray = new int[3];
intArray[0] = 2;
intArray[1] = 4;
intArray[2] = 6;
ArrayList al = new ArrayList();
for(int i=0; i < 7; i++)
{
al.add("test "+i);
}
System.out.println(al);
for(int x = intArray.length-1; (x != -1); x--)
{
System.out.println(al.remove(intArray[x]));
}
}
You should try to delete from the bottom of the ArrayList. So that the size
of the ArrayList doesn't effect the index of the objects
that we are trying to delete.

No comments: