如何通过包含对象的LinkedList重述 - Java的 [英] How to Iterate through LinkedList that contains Object - Java

查看:83
本文介绍了如何通过包含对象的LinkedList重述 - Java的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过我的LinkedList我添加的对象循环?

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()));

这是我得到的输出
[传感器@ 4d405ef7,传感器@ 6193b845,传感器@ 2e817b38,传感器@ c4437c4,传感器@ 433c675d,传感器@ 3f91beef]

the output that I get is [Sensor@4d405ef7, Sensor@6193b845, Sensor@2e817b38, Sensor@c4437c4, Sensor@433c675d, Sensor@3f91beef]

感谢您

推荐答案

您需要的 的toString() 方法中的传感器类。

@Override
public String toString() {
    return "id: "+ID+"; name: "+NAME+"; comments: "+ COMMENTS;
}

<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#toString%28java.lang.Object[]%29\"相对=nofollow> Arrays.toString(Object []对象A) 会打电话给您的每一个传感器对象的的toString()方法。

下面是一个传感器类推荐的变量名称更改的一个更完整的例子:

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

}

这篇关于如何通过包含对象的LinkedList重述 - Java的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆