Hello I have been trying to add a String
to a 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 wont let me make any new String
s. I can't modify my declaration of ipList[]
without a lot of modifications, what can I do?
Java arrays are of a fixed length (JLS-10.3. Array Creation says, in part, the array's length is available as a final
instance variable length
). But you can use Arrays.copyOf(T[], int)
to copy the array and make it one longer. As an example, something like,
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 is
[127.0.0.1]
[127.0.0.1, 192.168.2.1]
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 try to access Main.ipList[i + 1]
which equals Main.ipList[Main.ipList.length]
? This is guaranteed to throw the exception that you're seeing.
You state:
"I cant really change my declaring of ipList[] or it would mess up my whole project."
Sometimes there are times when you just have to take the plunge and mess everything up, and this looks to be one of them. If you need an expandable array, don't use an array, but rather an ArrayList<String>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With