为什么我在这里收到 IndexOutOfBoundsException 错误?

huangapple go评论86阅读模式
英文:

Why am i getting IndexOutOfBoundsException here?

问题

import java.util.*;

class two_strings_anagrams1 {
    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((Character) 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时,代码可以正常工作。异常的原因是什么,如何解决这个异常?

英文:
import java.util.*;

class two_strings_annagrams1 {
    public static boolean compute(String inp1, String inp2) {
        ArrayList&lt;Character&gt; hs = new ArrayList&lt;Character&gt;();
        for (int i = 0; i &lt; inp1.length(); i++) {
            hs.add(inp1.charAt(i));
        }
        System.out.println(hs);
        for (int j = 0; j &lt; 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?

答案1

得分: 0

我认为 hs.remove(inp2.charAt(j)) 的解析为 remove(int),而不是 remove(Character),因为编译器更倾向于将 char 扩展为 int,而不是将其装箱为 Character

如果您使用

hs.remove((Character) inp2.charAt(j))

这将消除歧义。

英文:

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.

huangapple
  • 本文由 发表于 2020年9月13日 17:52:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63869392.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定