Creating an Arraylist of Objects

JavaAndroidObjectArraylist

Java Problem Overview


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

Java Solutions


Solution 1 - Java

ArrayList<Matrices> list = new ArrayList<Matrices>();
list.add( new Matrices(1,1,10) );
list.add( new Matrices(1,2,20) );

Solution 2 - Java

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.

Solution 3 - Java

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.
 

}

Solution 4 - Java

We can create ArrayList of object , for this we declare ArrayList of specific Class type

    ArrayList<User> arr = new ArrayList<User>();

arr is arraylist of objects of class User .Here ArrayList arr can store object of User Class .

   arr.add(new User("Raja", 20));

Source : How to create List of Objects

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSamuelView Question on Stackoverflow
Solution 1 - JavaAaron SaundersView Answer on Stackoverflow
Solution 2 - JavaJorgesysView Answer on Stackoverflow
Solution 3 - Javauser9791370View Answer on Stackoverflow
Solution 4 - JavaAnuj DhimanView Answer on Stackoverflow