我是否可以动态增加数组的大小并保留数组中的旧值。我们不知道数组的大小,因为用户不断插入值,我们必须在每次输入后更改数组长度。因此,如果有人有比我想要实现的更好的选择,我将不胜感激。
private static String[] hotelName;
private static int lent=1;
public FiletoArray()
{
hotelName=new String[lent];
initComponents();
}
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
insertHotel(this.jTextField1.getText());
this.jLabel3.setText("" + lent);
lent=lent+1;
for(int a=0;a<lent;a++)
{
this.jTextArea1.setText(hotelName[a] + "\n");
}
}
public static void insertHotel(String hotelValue)
{
hotelName[lent-1]=hotelValue;
}
最佳答案
使用 ArrayList如果可能的话,它将动态增长以适应其数据。如果您需要使用数组,那么您需要分配一个新的(更大的)数组,然后使用 System.arraycopy复制旧数组的内容。
关于java - 动态插入数组的大小并将旧值保留在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16064449/