簡體   English   中英

在Java中引用類對象

[英]Referencing a class object in java

可以說我有一個班級用戶:

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,其中包含所有創建的對象。 我是否有辦法在另一個方法textWindow.append("localhost." + ... + getDateTime() + " > ");使用connectionID變量再次與該對象相關聯textWindow.append("localhost." + ... + getDateTime() + " > "); ...部分是我要在其上使用getConnectID()方法的部分。

不要將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

一種可能的解決方案是將connectionID的類型從Integer更改為您創建的類

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的情況下與用戶建立聯系。

假設connectID對每個User唯一。 您可以遍歷accounts並比較connectID

public User getUser(int connectID){
    for (User user : accounts){
        if (user.getConnectID()==connectID){
            return user;
        }
    }
    return null;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM