Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Adding string to a string array [duplicate]

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?

like image 717
randomnessthatsfunny Avatar asked Nov 28 '15 05:11

randomnessthatsfunny


2 Answers

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]
like image 66
Elliott Frisch Avatar answered Oct 21 '22 13:10

Elliott Frisch


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

like image 7
Hovercraft Full Of Eels Avatar answered Oct 21 '22 11:10

Hovercraft Full Of Eels