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。 在这种情况下如何进步?
答案 0 :(得分:11)
不,数组不是长度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(...);
答案 1 :(得分:1)
新数组的长度只有 3 。旧数组变为无效。尝试写入这个新数组的第4位将是超出界限并导致异常。
在添加新项目之前,您必须将数组项添加到List
。
答案 2 :(得分:0)
String splitThis = "Hello, World, There";
arr = splitThis.split(",");
这将创建一个新数组并将其分配给arr变量,覆盖先前初始化的数组。新数组将有三个元素
arr[0] = "Hello"
arr[1] = " World"
arr[2] = " There"
arr[3]
会抛出异常。