问题
How can i iterate through my LinkedList which i added Objects?
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);
` The problem that i am having is that i can add the Sensor Object to the Linked List but when I try to loop through it i get a reference as a result instead of the object or its values.
//display the results of the Linked List
System.out.println(Arrays.toString(sensors.toArray()));
the output that I get is [Sensor@4d405ef7, Sensor@6193b845, Sensor@2e817b38, Sensor@c4437c4, Sensor@433c675d, Sensor@3f91beef]
Thank you
回答1:
You need a toString() method in your Sensor
class.
@Override
public String toString() {
return "id: "+ID+"; name: "+NAME+"; comments: "+ COMMENTS;
}
Arrays.toString(Object[] a) will call each of your Sensor
object's toString()
method.
Here's a more complete example of a Sensor
class with recommended variable name changes:
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;
}
}
来源:https://stackoverflow.com/questions/28994299/how-to-iterate-through-linkedlist-that-contains-object-java