【发布时间】:2011-04-28 07:23:33
【问题描述】:
如何用对象填充 ArrayList,其中每个对象都不同?
【问题讨论】:
-
对这些类型的元素使用通用类。 Use the link for generic classes
标签: java android object arraylist
如何用对象填充 ArrayList,其中每个对象都不同?
【问题讨论】:
标签: java android object 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.
【讨论】:
如果您想允许用户将一堆新的 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.
}
【讨论】: