How to remove specific integer item from an ArrayList.

Problem: Given an array of integer values how to remove specific item from it.

As per the java api we have two methods for removing items from a list.

  • E remove(int index): It return the element which get deleted from the specified index.
  • boolean remove(Object o): It returns true if the specified item gets deleted from the list but the item to be deleted should of type object.

Lets look into the example code.

def list = [2,5,6,8] // shorthand to declare ArrayList in groovy
def item = list.remove(8) // java.lang.IndexOutOfBoundsException will be thrown since array size is 4
def item1 = list.remove(2) // will return 6 since 6 is at index 2
def status  = list.remove(8 as Object) // will return true if item deleted else return false
println list // [2,5]

 

Groovy provides ‘as’ keyword for type casting hence the above remove method removes specific item from the given list. 

For achieving the same thing in java one can use the below mentioned code:

list.remove((Object) 8)