在java中引用类对象

时间:2016-07-29 23:09:56

标签: java object

假设我有一个班级用户:

public class User {
    String userID;
    String password;
    Integer connectID;
    String name;

    public User(String Name, String ID, String Pass, Integer connect) {
        userID = ID;
        password = Pass;
        connectID = connect;
        name = Name;
    }

    public String getUserID() {
        return userID;
    }

    public String getPassword() {
        return password;
    }

    public Integer getConnectID() {
        return connectID;
    }

    public String getName() {
        return name;
    }
}

我有一段代码,它接受某个对象的connectID并将其放入变量connectionID = (accounts.get(i)).getConnectID();,其中accounts是一个包含所有创建对象的ArrayList。我是否可以使用connectionID变量在另一个方法textWindow.append("localhost." + ... + getDateTime() + " > ");中再次与该对象关联,其中...部分是我要使用的getConnectID()部分var imageNames = ["giphy-1 .jpg","giphy-2 .jpg", "giphy-3 .jpg", "giphy-4 .jpg", "giphy-5 .jpg"] 1}}方法。

3 个答案:

答案 0 :(得分:1)

不要将connectionID存储为变量。它已存储在User对象中。相反,将User存储为变量,以便稍后再次访问它的内容:

//Before the for loop, in a wider scope, declare the User:
User user;
//Then, in the for loop, initialize it:
user = accounts.get(i);
//As it was declared outside the for loop, it can be accessed later:
textWindow.append("localhost." + "User ID: " + user.getConnectionID() + " at " + getDateTime() + " > ");//or however you wish to format it

答案 1 :(得分:0)

此处的一种可能解决方案是将connectionID的类型从Integer更改为您创建的类<​​/ p>

class ConnectionID {

    private final Integer id;
    private final User user;

    ConnectionID(final Integer id,
                 final User user) {
        this.id = id;
        this.user = user;
    }

    public getUser() {
        return this.user;
    }

}

现在,您可以在给定连接ID的情况下与用户联系。

答案 2 :(得分:0)

假设UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Launch With Options" message:[launchOptions description] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; 对每个connectID都是唯一的。您可以遍历User并比较accounts

connectID