你好,我一直在试图将添加String
到String[]
。这就是我所拥有的
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);;
}
但是,我不断获得帮助,java.lang.ArrayIndexOutOfBoundsException
因为它不会让我提出任何新要求String
。ipList[]
没有大量修改就无法修改我的声明,该怎么办?
Java数组的长度是固定的(JLS-10.3。Array Creation表示,数组的长度部分可以作为final
实例变量使用length
)。但是,您可以Arrays.copyOf(T[], int)
用来复制数组,并使其更长。举例来说,
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));
输出为
[127.0.0.1]
[127.0.0.1, 192.168.2.1]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句