Een arraylijst met objecten maken

Hoe vul ik een ArrayList met objecten, waarbij elk object erin anders is?


Antwoord 1, autoriteit 100%

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

Antwoord 2, autoriteit 24%

Een arraylijst met objecten maken.

Maak een array om de objecten op te slaan:

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

In één stap:

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

of

MyObject myObject = new MyObject (1, 2, 3); //Create a new object.
list.add(myObject); // Adding it to the list.

Antwoord 3, autoriteit 4%

Als u een gebruiker wilt toestaan een aantal nieuwe MyObjects aan de lijst toe te voegen, kunt u dit doen met een for-lus:
Laten we zeggen dat ik een ArrayList van Rectangle-objecten aan het maken ben, en elke Rectangle heeft twee parameters: lengte en breedte.

//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.

}

Other episodes