-1

I was confused with basic Java where I was trying to use ArrayList which did not work but once I switched to HashSet ,it worked flawlessly.

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class TestJava {
    public static void main(String[] args) {
        char p = 'p';
        List<Character>  list = new ArrayList<>();
        list.add(p);
        
        Set<Character> set = new HashSet<>();
        set.add(p);
        
        System.out.println(list.remove(p));
        System.out.println(set.remove(p));
    }
}

In above example , I added a character in list and Set and after I tried to remove same character from list , it failed with IndexOutOfBound Exception whereas Set worked.

Why list is not simply removing character?

Shashi
  • 2,686
  • 7
  • 35
  • 67
  • Try printing `System.out.println((int) p);` you will see that the result us 112 and you are trying to remove object at index 112 while from the Set you are removing Obect with value 'p'. – f.trajkovski Jul 26 '21 at 15:49

1 Answers1

4

It happens because of the following:

  • Set interface exposes one method which is boolean remove(Object o)
  • List interface exposes two methods, one is E remove(int index) and the other one is boolean remove(Object o)

Since your p is a char, in the case of List you're colliding with the first method: the compiler interprets you're passing an int (the int value of char p being 112), and since your list doesn't have any element at index 112, you're crashing.

In the case of Set though, there's not such ambiguity and so it's removing it.

It is un unfortunate case. To stop the compiler doing that, you will have to, as suggested by @OH GOD SPIDERS, declare the variable to boxed Character instead of primitive char.

Matteo NNZ
  • 11,930
  • 12
  • 52
  • 89
  • 2
    Just to add: Declaring the variable as the object type `Character p` instead of the primtive char will result in the expected behaviour and not treat the character as an int. – OH GOD SPIDERS Jul 26 '21 at 15:50
  • @OHGODSPIDERS well seen, I had casted to Object but yours is way better! – Matteo NNZ Jul 26 '21 at 15:51
  • The main problem here is you are passing the primitive type. > char p = ‘p’; While removing, there is method remove(int) which other answer pointed. Since you are hitting to remove with primitive type, it is converted to int. To avoid this >Character p = 'p’; Use above, this ensures you are passing object. – Siva Srinivasa Rao M Jul 26 '21 at 15:54