创建一个对象的ArrayList

61

如何用不同的对象填充一个ArrayList?


使用泛型类来处理这些类型的元素。 请使用此链接了解泛型类 - Raj
参考泛型类。 - Raj
3个回答

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

20

如何创建一个对象数组列表。

创建一个数组来存储对象:

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

在一个步骤中:

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

MyObject myObject = new MyObject(1, 2, 3); 这将调用MyObject类的构造函数,该构造函数有3个参数。问题是如何创建包含多个不同对象的ArrayList。我想知道为什么这个问题有20个赞。 即使这样也会创建一个对象并将其添加到列表中: list.add(new MyObject(1, 2, 3)); - Harish Kumar Saini

4

如果您想允许用户添加大量新的MyObjects到列表中,可以使用for循环来实现: 假设我正在创建一个Rectangle对象的ArrayList,每个Rectangle都有两个参数-长度和宽度。

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

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接