Does Java’s split overwrite the length of the array, even if it is pre initialized?

String [] arr = {" "," "," "};  // String arr = new String[4];
String [] arr = {" "," "," "};  // String arr = new String[4];
String splitThis = "Hello,World,There";
arr = splitThis.split(","); 
arr[3] = "YAY";

The fourth line throws an array index out of bounds exception Even if the length of the array is 4 How to make progress in this situation?

Solution

No, the array is not length 4 The array length is 3 because it is the result of the split operation

Your code is really just:

String splitThis = "Hello,There";
String[] arr = splitThis.split(","); 
arr[3] = "YAY";

After the assignment of a variable is completed, its previous value is not important at all The split method returns a reference to an array, and you assign the reference to arr. the split method does not know the previous value of the variable - it operates on the value completely independently of you later - so it does not just fill part of the existing array

If you want that behavior, you can use something like this:

String[] array = { " "," " }; // Or fill however you want
String splitThis = "Hello,There";
String[] splitResults = splitThis.split(",");
System.arraycopy(splitResults,array,Math.min(array.length,splitResults.length));

Maybe you want a list < string > so you can add items later:

String splitThis = "Hello,There";
List<String> list = new ArrayList<>(Arrays.asList(splitThis.split(","));
list.add(...);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>