String [] arr = {" "," "," "," "}; // String arr = new String[4];
String splitThis = "Hello, World, There";
arr = splitThis.split(",");
arr[3] = "YAY";
第四行抛出Array Index Out of bounds Exception。即使数组的长度为 4。 这种情况如何进展?
最佳答案
不,数组不是长度为 4。数组的长度为 3,因为它是拆分操作的结果。
您的代码实际上只是:
String splitThis = "Hello, World, There";
String[] arr = splitThis.split(",");
arr[3] = "YAY";
一旦您完成了对变量的赋值,它之前的值就不再重要了。 split
方法返回对数组的引用,您将该引用分配给 arr
. split
方法不知道变量的先前值 - 它完全独立于您之后对值所做的操作 - 因此它不仅仅是填充现有数组的一部分。
如果你想要那种行为,你可以使用这样的东西:
String[] array = { " ", " ", " ", " " }; // Or fill however you want
String splitThis = "Hello, World, There";
String[] splitResults = splitThis.split(",");
System.arraycopy(splitResults, 0, array, 0,
Math.min(array.length, splitResults.length));
或者您想要一个 List<String>
这样您就可以稍后添加项目:
String splitThis = "Hello, World, There";
List<String> list = new ArrayList<>(Arrays.asList(splitThis.split(","));
list.add(...);
关于java - 即使预先初始化,Java的拆分是否会覆盖数组的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24385050/