Reputation: 112
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.
Upvotes: 0
Views: 62
Reputation: 1246
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;
}
Upvotes: 0
Reputation: 38531
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.
Upvotes: 0
Reputation: 2193
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
Upvotes: 1