Java列表项
我使用下面的代码Java列表项,java,list,Java,List,我使用下面的代码 List<String> text = new ArrayList<String>(); text.add("Hello"); List text=new ArrayList(); text.add(“你好”); 所以这个列表只接受要添加的字符串,我怎样才能在一个列表中添加更多类型的变量,比如int和字符串,比如 在文本列表中添加一些矩形值,如 矩形名称、矩形宽度、矩形高度 因此,稍后我可以在循环中访问它们创建自己的矩形类并将这些值存储在其中 Lis
List<String> text = new ArrayList<String>();
text.add("Hello");
List text=new ArrayList();
text.add(“你好”);
所以这个列表只接受要添加的字符串,我怎样才能在一个列表中添加更多类型的变量,比如int和字符串,比如
在文本列表中添加一些矩形值,如
矩形名称、矩形宽度、矩形高度
因此,稍后我可以在循环中访问它们创建自己的
矩形
类并将这些值存储在其中
List<Rectangle> rectangles = new ArrayList<>();
rectangles.add(new Rectangle("Foo", 20, 30));
List矩形=新建ArrayList();
添加(新的矩形(“Foo”,20,30));
对Duncan的答案进行一点扩展,下面是创建矩形类的方法:
public class Rectangle {
private String name;
private int height;
private int width;
/**
* Create a rectangle by calling
* Rectangle myRect = new Rectangle("foo", 20, 10);
*/
public Rectangle(String name, int height, int width) {
this.name = name;
this.height = height;
this.width = width;
}
}
您需要向它添加访问器方法,以便可以检索名称、宽度和高度。这些方法通常是公共方法,命名为getName和getWidth(昵称为getter)。您可能还有一个返回区域的函数。这里有一个例子
public String getName() { return name; }
public int getHeight() { return height; }
public int getWidth() { return width; }
public String area() {
int area = height * width;
return "Rectangle " + name + " has an area " + area + ".";
}
您只需创建一个
类
,该类将包含所需的变量,并将该类用作列表
声明中的数据类型
例如:
class MyStructure{
int anInteger;
double aDouble;
string aString;
//Followed by any other data types you need.
//You create a constructor to initialize those variables.
public MyStructure(int inInt, double inDouble, string inString){
anInteger = inInt;
aDouble = inDouble;
aString = inString;
}
}
然后,当您拥有main或方法并声明一个列表时,您只需编写:
List<MyStructure> myList = new ArrayList<>();
myList.add(new MyStructure(5, 2.5, "Hello!"));
List myList=new ArrayList();
添加(新的MyStructure(5,2.5,“你好!”);
虽然创建类的答案当然是组织程序的更好方法,但问题的答案是创建一个对象类型列表。然后,您可以将项目添加到任何类型的列表中。要确定在运行时处理的类型,可以使用instanceof关键字。但非常清楚的是,这不是一个好的做法
List<Object> text = new ArrayList<String>();
text.add("Hello");
text.add(new Integer(10));
List text=new ArrayList();
text.add(“你好”);
添加(新整数(10));
为什么要这样做?用这些变量作为字段来编写一个类不是更好吗?如果他在ArrayList中存储矩形而不是只存储矩形名称会更好。是的,我在评论你的帖子时说他应该在ArrayList中存储rec的名称,这有点奇怪,因为你可以存储整个对象,这正是你最近添加的内容是的。如果真的需要,他们也可以在这个类中包装一个对象来封装高度和宽度(如果需要这个类的功能的话)。如果OP需要,该类还将提供来源。