Reputation: 19771
I have a class
Class A{
string a;
int b;
getters and setters of a and b;
}
I want to make a list of objects of class A. How is it possible in Java
I want to also set the values of a and b.
Upvotes: 0
Views: 2314
Reputation: 920
List<A> aList = new ArrayList<A>();
To set value
A a = new A();
a.setMethod("Hello World");
aList.add(a);
List out value
for(A aa : aList){
System.out.println(aa.getMethod());
}
Upvotes: 1
Reputation: 77910
A a new A();
a.setA("aaa");
a.setB(4);
List<A> aList = new ArrayList<A>();
aList.add(a);
/// ....
String a;
int b;
for(A a: aList){
a = a.getA();
b = a.getB();
}
Upvotes: 1
Reputation: 4065
List<A> aList = new ArrayList<A>();
A anObj = new A();
anObj.setA(1);
anObj.setB(1);
aList.add(anObj);
Upvotes: 1
Reputation: 2390
You can declare an array of type A
List<A> myList = new ArrayList<A>();
then Creat an A object
A a = new A();
a.setA = stringA; // or whatever you want to set on the object
then add that object to the array
myList.add(a);
Upvotes: 1
Reputation: 2351
A a = new A();
a.setA("bbb");
a.setB(88);
List<A> list = new ArrayList<A>();
list.add(a);
/////.....
Upvotes: 1
Reputation: 862
List is just an interface. So you can not instantiate a List
. You have to use classes that implements List
interface. For example ArrayList
.
You can try this out
ArrayList <A> listOfA = new ArrayList<A>(intitalCapacity);
Upvotes: 0
Reputation: 347314
You could use arrays...
A[] listOfA = new A[]{new A(), new A(), new A(), new A(), new A()};
A[] anotherListOfA = new A[5];
for (int index = 0; index < anotherListOfA.length; index++) {
anotherListOfA[index] = new A();
}
Check out Arrays for more details
You could use an implementation of List
List<A> listOfA = new ArrayList<>(5);
for (int index = 0; index < 5; index++) {
listOfA.add(new A());
}
Check out Collections for more details
Upvotes: 4