import java.util.*;
class two_strings_annagrams1 {
public static boolean compute(String inp1, String inp2) {
ArrayList<Character> hs = new ArrayList<Character>();
for (int i = 0; i < inp1.length(); i++) {
hs.add(inp1.charAt(i));
}
System.out.println(hs);
for (int j = 0; j < inp2.length(); j++) {
hs.remove(inp2.charAt(j));
}
System.out.println(hs);
if (hs.size() == 0) {
return true;
}
return false;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String inp = s.nextLine();
String inp2 = s.nextLine();
System.out.println(compute(inp, inp2));
}
}
When I use ArrayList or LinkedList I'm getting an IndexOutOfBounds Exception but when I use HashSet the code is working fine. What's the reason of exception and how the exception can be resolved?
I think hs.remove(inp2.charAt(j))
resolves to remove(int)
, not remove(Character)
, because the compiler prefers expanding a char
to an int
over boxing it to a Character
.
If you use
hs.remove((Character) inp2.charAt(j))
it will eliminate the ambiguity.