Java Adding a String to an Array of Strings

Hello, I am trying to add String to String[] . Here is what I have

 static String[] ipList = {"127.0.0.1", "173.57.51.111", "69.696.69.69"}; @Override public void actionPerformed(ActionEvent e) { String newIpGet = textfield.getText(); try { for ( int i = 0; i < Main.ipList.length; i++){ Main.ipList[i+1] = newIpGet.toString(); // <---- ***** Main.write(Main.ipList[i]); } } catch (IOException e1) { e1.printStackTrace(); } Main.amountOfIps = Main.amountOfIps + 1; System.out.println("Text Entered!"); System.out.println("There are now " +Main.ipList.length + " Ips."); textfield.setVisible(false); label.setVisible(true);; } 

But I keep getting java.lang.ArrayIndexOutOfBoundsException because it will not allow me to create new String s. I cannot change my ipList[] declaration without a lot of changes, what can I do?

+6
source share
3 answers

Java arrays have a fixed length ( JLS-10.3. Creating an array , in particular, the length of the array is available as the final instance variable length ). But you can use Arrays.copyOf(T[], int) to copy the array and make it longer. As an example, for example,

 String[] ipList = { "127.0.0.1" }; System.out.println(Arrays.toString(ipList)); int len = ipList.length; ipList = Arrays.copyOf(ipList, len + 1); ipList[len] = "192.168.2.1"; System.out.println(Arrays.toString(ipList)); 

Output

 [127.0.0.1] [127.0.0.1, 192.168.2.1] 
+10
source

What do you think will happen here:

 for ( int i = 0; i < Main.ipList.length; i++){ Main.ipList[i+1] = newIpGet.toString(); Main.write(Main.ipList[i]); } 

when i == Main.ipList.length - 1 and you are trying to access Main.ipList[i + 1] , which is equal to Main.ipList[Main.ipList.length] ? This ensures that you get the exception you see.

You declare:

"I cannot change my ipList [] declaration, otherwise it will ruin my entire project."

Sometimes there are times when you just need to plunge and ruin everything, and it looks like one of them. If you need an extensible array, do not use an array, but rather an ArrayList<String> .

+7
source

You can also use the ArrayList<String> from the java.util package! They have a variable length and therefore are not immuatable in length, like String[] . They also do this on the fly when you add or remove something.

0
source

All Articles