简体   繁体   中英

Referencing a class object in java

Lets say I have a class User:

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

And I have a section of my code which takes the connectID of a certain object and puts it into a varaible connectionID = (accounts.get(i)).getConnectID(); where accounts is an ArrayList holding all of the objects created. Would there be a way for me to use the connectionID variable to relate back to the object again in another method textWindow.append("localhost." + ... + getDateTime() + " > "); where the ... part is the part that I want to use the getConnectID() method on.

Don't store connectionID as a variable. It is already stored within the User object. Instead, store the User as a variable so it's contents can be accessed again later:

//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

One possible solution here is to change the type of connectionID from Integer to a class you create

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

}

Now you can relate back to the user, given a connection id.

Assuming that connectID is unique to each User . You could loop through the accounts and compare the connectID .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM