6

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 Strings. I can't modify my declaration of ipList[] without a lot of modifications, what can I do?

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 2
    Arrays have a fixed size. You either need to create a new array at the new size and copy everything over to it or use an `ArrayList`, which essentially does this – MadProgrammer Nov 28 '15 at 05:25

3 Answers3

10

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]
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
7

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>.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0

You also just could use an ArrayList<String> from the java.util package! These are of variable length and therefore not immuatable in length like an String[] is. Furthermore they do it "on the fly" when you add or remove something.

ToxiCore
  • 159
  • 1
  • 11