我如何遍历我添加了对象的LinkedList?
private LinkedList sensors = new LinkedList();
enter code here
//Constructor for my class is taking three arguments
public Sensor(int ID, String Name, String comments) {
this.ID = ID;
this.NAME = Name;
this.COMMENTS = comments;
}
//Then I query the database to get the values of the variables to create a new Object
ID = Integer.parseInt(dbResult.getString("sensorID") );
NAME = dbResult.getString("sensorName");
COMMENTS = dbResult.getString("sensorcomments");
//create a new sensor object
Sensor newSensor = new Sensor(ID, NAME, COMMENTS);
//add the sensor to the list
addSensor(newSensor);
`
我遇到的问题是我可以将传感器对象添加到“链接列表”,但是当我尝试遍历它时,得到的结果是引用而不是对象或其值。
//display the results of the Linked List
System.out.println(Arrays.toString(sensors.toArray()));
我得到的输出是
[Sensor @ 4d405ef7,Sensor @ 6193b845,Sensor @ 2e817b38,Sensor @ c4437c4,Sensor @ 433c675d,Sensor @ 3f91beef]
谢谢
最佳答案
在toString()
类中需要一个Sensor
方法。
@Override
public String toString() {
return "id: "+ID+"; name: "+NAME+"; comments: "+ COMMENTS;
}
Arrays.toString(Object[] a)
将调用每个Sensor
对象的toString()
方法。这是带有建议的变量名称更改的
Sensor
类的更完整示例:class Sensor {
private int id;
private String name;
private String comments;
public Sensor(int id, String name, String comments) {
this.id = id;
this.name = name;
this.comments = comments;
}
@Override
public String toString() {
//You can change how to the string is built in order to achieve your desired output.
return "id: "+ID+"; name: "+name+"; comments: "+ comment;
}
}
关于java - 如何遍历包含对象的LinkedList-Java,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28994299/