Java 如何在数组中添加元素?

Java 如何在数组中添加元素?,java,arrays,Java,Arrays,请参见代码示例: public Core() { class1 = new int[5]; //declares array for 5 class class2 = new int[5]; //delcares array for 5 class System.out.println("Please type 1 for First Classe:"); select = input.nextInt(); if(select == 1)

请参见代码示例:

public Core()
{   
    class1 = new int[5]; //declares array for 5 class 
    class2 = new int[5]; //delcares array for 5 class

    System.out.println("Please type 1 for First Classe:");
    select = input.nextInt();

    if(select == 1)
    {

    }

}
好的。如果用户选择选项1,则在数组的内存中占据一个位置。例如:

class1 = new int[4];

或者,如果大小写超出内存,则会显示一条消息。

您不能将元素添加到数组中-创建后它们的大小是固定的。我想您最好使用一些描述的列表实现,比如ArrayList


老实说,现在还不清楚你想做什么,但几乎可以肯定的是,使用集合而不是数组会让你的生活更轻松。

你在找数组列表吗

import java.util.*; 
ArrayList list = new ArrayList(); 
ArrayList具有动态大小,因此您可以在运行时添加和删除数组的成员

list.add(someObject); //add object
list.remove(2); //remove object by index, objects will 'slide' down to fill the gap
int size = list.size(); //get size of ArrayList
String object = list.get(3) //get object in array, not always string
你为什么不直接用它来代替呢


请注意,如果以后要再次删除该元素,最好不要添加该元素。但这只是一个简单的说明。

似乎您希望在数组中插入元素,直到数组充满为止

您声明的不是动态数组,而是静态数组。这意味着一旦声明int[]class1=new int[5],您将只有5个插槽,您必须注意插入它们的位置

class1[0] = value
这一个在数组的第一个插槽中插入值,而下一个:

class1[5] = something
这可能是错误的,因为您试图将数组的第六个元素设置为大小5。您需要做的是添加元素,直到填充数组为止。您可以通过使用跟踪当前位置的索引值来完成此操作:

int指数=0; int[]class1=新的int[5]

....
if (index < class1.length)
  class1[index] = value
else
  //ARRAY IS FULL!
或者,您可以检查阵列本身:

int i = 0;
boolean placed = false;
while (i < class1.length && class1[i] != null)
  ++i;
if (i < class1.length)
  class1[i] = value;
else
  //ARRAY IS FULL!

但我的建议是明确使用ArrayList,并将最大大小作为变量。

我不明白你在说什么。你的问题是什么?嘿,谢谢回答!但是,不,我使用的是导入ArrayList。我正在创建so:int[]class1//声明整数数组int[]class2;我不确定我是否理解你的问题,但我还是有问题。我希望在数组中添加一个数字,例如:ifselect==1{class1[0]=1;}System.out.printlnclas1:;int i=0;当然,您只分配给index=0,并且只打印class1[0]index=0。相反,您的打印可以是System.out.printlnclas1[i];。但是,你不应该这样做,你应该“ArrayList”并添加到它们中。我很快会在回答中写一个例子。
int i = 0;
boolean placed = false;
while (i < class1.length && class1[i] != null)
  ++i;
if (i < class1.length)
  class1[i] = value;
else
  //ARRAY IS FULL!