参见英文答案 >
Java dynamic array sizes?18个
您好我一直在尝试将String添加到String [].这是我的,
您好我一直在尝试将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,因为它不会让我创建任何新的字符串.我无法修改我的ipList []声明而无需进行大量修改,我该怎么办?
解决方法
Java数组具有固定长度(
JLS-10.3. Array Creation表示,部分数据的长度可用作最终实例变量长度).但您可以使用
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]