Tworzenie tablicy obiektów

Jak wypełnić Arraylistę obiektami, przy czym każdy obiekt wewnątrz jest inny?

Author: Samuel, 2010-10-21

3 answers

ArrayList<Matrices> list = new ArrayList<Matrices>();
list.add( new Matrices(1,1,10) );
list.add( new Matrices(1,2,20) );
 60
Author: Aaron Saunders,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-10-20 21:44:52

Jak utworzyć Arraylistę obiektów.

Tworzenie tablicy do przechowywania obiektów:

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

W jednym kroku:

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

Lub

MyObject myObject = new MyObject (1, 2, 3); //Create a new object.
list.add(myObject); // Adding it to the list.
 13
Author: Jorgesys,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-03 21:56:53

Jeśli chcesz zezwolić użytkownikowi na dodanie kilku nowych obiektów MyObjects do listy, możesz to zrobić za pomocą pętli for: Załóżmy, że tworzę Arraylistę obiektów prostokątnych, a każdy prostokąt ma dwa parametry-długość i szerokość.

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

}

 0
Author: user9791370,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-15 05:02:16