Abhishek Goel
Abhishek Goel

Reputation: 19771

how to make a list of class in JAVA

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

Answers (7)

gjman2
gjman2

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

Maxim Shoustin
Maxim Shoustin

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

Arvind Sridharan
Arvind Sridharan

Reputation: 4065

List<A> aList = new ArrayList<A>();

A anObj = new A();
anObj.setA(1);
anObj.setB(1);

aList.add(anObj);

Upvotes: 1

Sean F
Sean F

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

sunysen
sunysen

Reputation: 2351

A a = new A();
a.setA("bbb");
a.setB(88);

List<A> list = new ArrayList<A>();
list.add(a);
/////.....

Upvotes: 1

Debobroto Das
Debobroto Das

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

MadProgrammer
MadProgrammer

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

Related Questions