61

How do I fill an ArrayList with objects, with each object inside being different?

Samuel
  • 4,337
  • 3
  • 29
  • 35
  • Use Generic class for these type of elements. [Use the link for generic classes](https://stackoverflow.com/questions/14391027/java-generics-in-android) – Raj Jun 12 '17 at 09:47
  • Refer Generic classes [enter link description here](https://stackoverflow.com/questions/14391027/java-generics-in-android) – Raj Jun 12 '17 at 09:48

3 Answers3

86
ArrayList<Matrices> list = new ArrayList<Matrices>();
list.add( new Matrices(1,1,10) );
list.add( new Matrices(1,2,20) );
Aaron Saunders
  • 33,180
  • 5
  • 60
  • 80
20

How to Creating an Arraylist of Objects.

Create an array to store the objects:

ArrayList<MyObject> list = new ArrayList<MyObject>();

In a single step:

list.add(new MyObject (1, 2, 3)); //Create a new object and adding it to list. 

or

MyObject myObject = new MyObject (1, 2, 3); //Create a new object.
list.add(myObject); // Adding it to the list.
Community
  • 1
  • 1
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
  • ````MyObject myObject = new MyObject (1, 2, 3);```` This will call the constructor of MyObject class with 3 parameters. The question is about creating ArrayList with multiple different objects. I wonder why this has 20 upvotes. Even this will create one object and add that to list: ````list.add(new MyObject (1, 2, 3)); ```` – Harish Kumar Saini Mar 09 '23 at 04:04
4

If you want to allow a user to add a bunch of new MyObjects to the list, you can do it with a for loop: Let's say I'm creating an ArrayList of Rectangle objects, and each Rectangle has two parameters- length and width.

//here I will create my ArrayList:

ArrayList <Rectangle> rectangles= new ArrayList <>(3); 

int length;
int width;

for(int index =0; index <3;index++)
{JOptionPane.showMessageDialog(null, "Rectangle " + (index + 1));
 length = JOptionPane.showInputDialog("Enter length");
 width = JOptionPane.showInputDialog("Enter width");

 //Now I will create my Rectangle and add it to my rectangles ArrayList:

 rectangles.add(new Rectangle(length,width));

//This passes the length and width values to the rectangle constructor,
  which will create a new Rectangle and add it to the ArrayList.

}

user9791370
  • 339
  • 1
  • 10