Friday, January 3, 2020

[Java][Resolved] java arraylist remove by int value

public int singleNum(int[] nums) {
  ArrayList<Integer> al = new ArrayList<Integer>();
    for(int num: nums){
      if(!al.contains(num)){
        al.add(num);
      }else{
        al.remove(num);
      }
  }
  return al.get(0);
}

Run and get "IndexOutOfBoundsException" on al.remove(num);, this line call remove(int index) but not remove(Object o) so cause this error.

For instance, content of nums is new int[]{99,98}, and al.remove(99) means remove the item in ArrayList named al at index 99. This item not exist and exeception throws.
What we should do is cast variable num from privaitive type to an Integer object :
public int singleNum(int[] nums) {
  ArrayList<Integer> al = new ArrayList<Integer>();
    for(int num: nums){
      if(!al.contains(num)){
        al.add(num);
      }else{
        al.remove(Integer.valueOf(num));
      }
  }
  return al.get(0);
}

Reference
https://stackoverflow.com/questions/21795376/java-how-to-remove-an-integer-item-in-an-arraylist
https://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html)

No comments :

Post a Comment