Casting char->Character in ArrayList#remove() - Why?

73 views Asked by At
import java.util.*;

public class rearrange_palindrome {

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        String st=sc.nextLine();

        ArrayList<Character> ar = new ArrayList<Character>();

        for (int i=0;i<st.length();i++){
            if (ar.contains(st.charAt(i)))
            ar.remove((Character)st.charAt(i));//why did they use type casting?
            else
            ar.add(st.charAt(i));
        }
        if (st.length()%2==0 && ar.isEmpty()==true || st.length()%2==1 && ar.size()==1)
        System.out.println("Palindrome");
        else
        System.out.println("Not a palindrome");
    }
}

please tell, me the reason why did they use type casting, I've commented that line.

2

There are 2 answers

0
carter On

Removing both chars and ints can lead to logic errors when using the remove(T e) because of the overloaded method remove(int index) of the ArrayList class. Casting to their wrapper class avoids this.

0
Tarik On

The ArrayList class uses generics to specify that it contains a instances of Character. The casting allows automatic boxing char into a Character instance. See https://www.geeksforgeeks.org/autoboxing-unboxing-java/ The reason behind this, being that unlike in C#, generics are supported for classes but not intrinsic types such as int, char...