[英]Add elements to a custom class list
I have created a custom class: 我创建了一个自定义类:
package mypackage;
public class myClass {
public int a;
public int b;
public int c;
public myClass(int a, int b, int c){
this.a = a;
this.b = b;
this.c = c;
}
}
I then create an arraylist in another class file: 然后,我在另一个类文件中创建一个arraylist:
ArrayList<myClass > myArrayList= new ArrayList<myClass>();
But how do I add data to it? 但是,如何向其中添加数据? I want to do something like this:
我想做这样的事情:
for(int indexer = 0; indexer < count; indexer++){
myArrayList[indexer].a = 5;
myArrayList[indexer].b = 5;
myArrayList[indexer].c = 5;
}
This obviously doesn't work. 这显然行不通。 How is this suppose to work?
这应该如何工作?
Look, your myArrayList
is an ArrayList of myClass
. 看,您的
myArrayList
是myClass
的ArrayList 。 So to add elements into myArrayList
you need myCLass
objects. 因此,要将元素添加到
myArrayList
,需要myCLass
对象。 (Offtopic: Please use capital letter for class naming, say MyClass
instead of myClass
). (主题:请使用大写字母表示类的名称,例如说
MyClass
而不是myClass
)。 For example, 例如,
myClass myClassObject = new myClass(5, 5, 5);
Now use add() to add myClassObject
object into your ArrayList 现在使用add()将
myClassObject
对象添加到ArrayList中
myArrayList.add(myClassObject);
If you want to be able to access a,b,c
variables you got to declare them like this 如果您希望能够访问
a,b,c
变量,则必须这样声明它们
public static int a; public static int b;
and so on. 等等。 Another option is to create
getters and setters:
另一种选择是创建
getters and setters:
private int a;
public int getA() {
return a;
}
public void setA(int a) {
this.a=a;
}
Otherwise, use the List
add method myArrayList.add(...);
否则,请使用
List
添加方法myArrayList.add(...);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.