Java 创建对象的 Arraylist

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3982550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 07:53:33  来源:igfitidea点击:

Creating an Arraylist of Objects

javaandroidobjectarraylist

提问by Samuel

How do I fill an ArrayList with objects, with each object inside being different?

如何用对象填充 ArrayList,其中每个对象都不同?

采纳答案by Aaron Saunders

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

回答by Jorgesys

How to Creating an Arraylist of Objects.

如何创建对象的 Arraylist。

Create an array to store the objects:

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

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

In a single step:

只需一步:

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

or

或者

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

回答by user9791370

If you want to allow a user to add a bunch of new MyObjects to the list, you can do it with a for loop: Let's say I'm creating an ArrayList of Rectangle objects, and each Rectangle has two parameters- length and width.

如果您想让用户向列表中添加一堆新的 MyObject,您可以使用 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.

}

}