Java ArrayList of Object';add()方法不工作
我是JAVA新手,我知道我面临着一个初学者的问题 通俗易懂=>我正在尝试创建对象的ArrayList,并在需要时在数组中添加新对象。 好的,这是我的代码的精简版本Java ArrayList of Object';add()方法不工作,java,oop,arraylist,Java,Oop,Arraylist,我是JAVA新手,我知道我面临着一个初学者的问题 通俗易懂=>我正在尝试创建对象的ArrayList,并在需要时在数组中添加新对象。 好的,这是我的代码的精简版本 package ACP.Employee; //created package import java.util.ArrayList; //imported arraylist class import ACP.Employee.EmployeeClass; //imported employee class of sa
package ACP.Employee; //created package
import java.util.ArrayList; //imported arraylist class
import ACP.Employee.EmployeeClass; //imported employee class of same package
public class ClientClass
{
ArrayList<EmployeeClass> empArray = new ArrayList<EmployeeClass>(); //created a new Array List
public static void main (String[] args)
{
int objcount = 0; //variable to store objct count
empArray.add(objcount, EmployeeClass obj);
}
}
但是仍然存在以下错误
- 无法对非静态数组进行静态引用
您的代码有两个问题
ClientClass
的成员。只有当该成员是静态的时,才可能这样做。由于empArray
没有任何属性,因此它将默认为非静态的包private。您必须通过将其声明为静态,使其在静态上下文中可访问:
static ArrayList empArray=new ArrayList()编码>
或创建ClientClass的实例并访问其成员
ArrayList<EmployeeClass> empArray = new ArrayList<EmployeeClass>();
public static void main(String[] args) {
ClientClass t = new ClientClass();
t.empArray.add(new Employee());
}
ArrayList empArray=new ArrayList();
公共静态void main(字符串[]args){
ClientClass t=新的ClientClass();
t、 添加(新员工());
}
通过
static
方法,您只能访问static
字段。通过
notstatic
方法,您可以访问所有字段。例如 因此,在您的示例中,
empArray
应该是static
public class ClientClass
{
static ArrayList<EmployeeClass> empArray = new ArrayList<EmployeeClass>();
public static void main (String[] args)
{
int objcount = 0; //variable to store objct count
empArray.add(objcount, new EmployeeClass());
empArray.add(new EmployeeClass());
}
}
public类ClientClass
{
静态ArrayList empArray=新ArrayList();
公共静态void main(字符串[]args)
{
int objcount=0;//用于存储objct计数的变量
add(objcount,newEmployeeClass());
添加(newEmployeeClass());
}
}
在emprarray
变量的声明前面放置一个静态
。如下所示:static ArrayList empArray=new…
empArray是类的成员,main是静态成员,因此,这是禁止的静态方法无法访问非静态成员。确定了。美好的但我仍然对这里的概念感到困惑。对不起,伙计们,请不要生气:-谢谢你们的精心设计。但关于第二点,编译器编译我的代码时没有任何错误。我也不认为我的声明有任何问题,因为简单地说,我正在创建类型为“EmployeeClass”的ArrayList。为什么不应该呢?正如我所读到的,ArrayList=>其中T是模板(可以容纳任何数据类型)。
private int i = 0;
private static int j = 0;
public void increment()
{
i++; // correct
j++; // correct
}
public static void staticIncrement()
{
i++; // compilation error
j++; // correct
}
public class ClientClass
{
static ArrayList<EmployeeClass> empArray = new ArrayList<EmployeeClass>();
public static void main (String[] args)
{
int objcount = 0; //variable to store objct count
empArray.add(objcount, new EmployeeClass());
empArray.add(new EmployeeClass());
}
}