如何用不同的对象填充一个ArrayList?
ArrayList<Matrices> list = new ArrayList<Matrices>();
list.add( new Matrices(1,1,10) );
list.add( new Matrices(1,2,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如果您想允许用户添加大量新的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.
}