[英]Why am i getting IndexOutOfBoundsException here?
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));
}
}
当我使用 ArrayList 或 LinkedList 时,我得到一个 IndexOutOfBounds 异常,但是当我使用 HashSet 时,代码工作正常。 异常的原因是什么以及如何解决异常?
我认为hs.remove(inp2.charAt(j))
解析为remove(int)
,而不是remove(Character)
,因为编译器更喜欢将char
扩展为int
而不是将其装箱为Character
。
如果你使用
hs.remove((Character) inp2.charAt(j))
它将消除歧义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.