Java adds a string to a string array

See English answer > java dynamic array sizes? 18

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 always get Java Lang. ArrayIndexOutOfBoundsException, because it won't let me create any new strings I can't modify my iplist [] declaration without a lot of modification. What should I do?

Solution

Java arrays have a fixed length (jls-10.3. Array creation indicates that the length of some data can be used as the length of the final instance variable) But you can use arrays Copyof (t [], int) copies the array and makes it longer For example, 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]
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
分享
二维码
< <上一篇
下一篇>>