如何遍历包含Object的LinkedList - Java

时间:2015-03-11 18:13:16

标签: java arrays tostring

如何迭代我添加了Objects的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]

谢谢

1 个答案:

答案 0 :(得分:1)

您需要在Sensor课程中使用toString()方法。

@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;
    }

}