我真的很困惑为什么 ArrayList.remove() 会导致堆栈溢出:D
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 98 out of bounds for length 3
Run Code Online (Sandbox Code Playgroud)
但这不是“C”。char 在语义上更接近 Character 而不是 int。
我的代码(将字符串 s 转换为 t 的最少步骤数):
public class Solution {
public int minSteps(String s, String t) {
ArrayList<Character> list = new ArrayList<Character>();
for (char c : t.toCharArray()) {
list.add(c);
}
System.out.println(list.toString());
for (char c : s.toCharArray()) {
System.out.println("trying to remove " + c);
list.remove(c);
System.out.println(" result: " + list);
}
return list.size();
}
public static void main(String[] args) {
Solution sol = new Solution();
String s = "bab";
String t = "aba";
System.out.println("minSteps: s " + sol.minSteps(s, t));
}
public Solution() {
}
}
Run Code Online (Sandbox Code Playgroud)
控制台输出是
[a, b, a]
trying to remove b
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 98 out of bounds for length 3
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:373)
at java.base/java.util.ArrayList.remove(ArrayList.java:502)
at com.sandbox.Solution.minSteps(Solution.java:25)
at com.sandbox.Solution.main(Solution.java:35)
Run Code Online (Sandbox Code Playgroud)
奇怪的是当我尝试做
boolean b = list.remove(c);
Run Code Online (Sandbox Code Playgroud)
它不会编译!
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types: java.lang.Character cannot be converted to boolean
at com.sandbox.Solution.minSteps(Solution.java:25)
at com.sandbox.Solution.main(Solution.java:35)
Run Code Online (Sandbox Code Playgroud)
当我将 c 显式转换为 Character 时,它会起作用。这告诉我自动装箱在这里不起作用!
boolean b = list.remove(Character.valueOf(c));
[a, b, a]
trying to remove b
result: [a, a]
trying to remove a
result: [a]
trying to remove b
result: [a]
minSteps: s 1
Run Code Online (Sandbox Code Playgroud)
List
有2remove
种方法:
remove(c)
可以通过将char
值扩大为 anint
或将char
值自动装箱为 a来调用它们中的任何一个Character
。
出于向后兼容性的原因,编译器总是喜欢简单的加宽而不是自动装箱,因此编译器选择进行调用remove((int) c)
。
要强制它调用另一个方法,请执行以下操作之一:
装箱char
自己:
remove(Character.valueOf(c))
Run Code Online (Sandbox Code Playgroud)使用演员强制自动装箱:
remove((Character) c)
Run Code Online (Sandbox Code Playgroud)如果您不喜欢remove
通话中的额外内容,您也可以执行以下操作之一:
在循环中触发自动装箱:
for (Character c : s.toCharArray())
Run Code Online (Sandbox Code Playgroud)在单独的语句中触发自动装箱:
Character cBoxed = c;
list.remove(cBoxed);
Run Code Online (Sandbox Code Playgroud) 归档时间: |
|
查看次数: |
110 次 |
最近记录: |