I have a Java hashmap, to which multiple variables were added(ex.):
class client {
public static int clientIdentifier;
public static String clientName;
public static String clientFamilyname;
public static String clientBirthdate;
}
Inside the main method:
client newclient = new client();
HashMap<Integer, String> clients = new HashMap<>();
clients.put(newclient.clientIdentifier,
newclient.clientName +
newclient.clientFamilyname +
newclient.clientBirthdate
Where new client.clientIdentifier is the key and newClient.clientName/Familyname/Birthdate are already defined. They belong to an object newclient, it belonging to the class client
Is there any way to get only the value clientName from that hashmap, to compare later?
Looking for something like:
String requiredName = clients.get(scannedID, newclient.clientName);
(I know that it is totally wrong, but just to have an idea)
Thank you very much!
You need to make all the fields in Client
non-static first! You'd want each instance of Client
to have a different ID, name, and birthday, right?
Instead of using a HashMap<Integer, String>
, use a HashMap<Integer, Client>
:
Client newclient = new Client();
HashMap<Integer, Client> clients = new HashMap<>();
clients.put(newclient.clientIdentifier, newclient);
Now you can just do:
String requiredName = clients.get(scannedID).clientName;
But really though, the fields in the class Client
should all be private and should be accessed via getters and setters. You also should not be able to reset the client's clientIdentifier
as that is the map's key.
Client
should look like this:
class Client {
private int clientIdentifier;
private String clientName;
private String clientFamilyname;
private String clientBirthdate;
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getClientFamilyname() {
return clientFamilyname;
}
public void setClientFamilyname(String clientFamilyname) {
this.clientFamilyname = clientFamilyname;
}
public String getClientBirthdate() {
return clientBirthdate;
}
public void setClientBirthdate(String clientBirthdate) {
this.clientBirthdate = clientBirthdate;
}
public int getClientIdentifier() {
return clientIdentifier;
}
public Client(int clientIdentifier, String clientName, String clientFamilyname, String clientBirthdate) {
this.clientIdentifier = clientIdentifier;
this.clientName = clientName;
this.clientFamilyname = clientFamilyname;
this.clientBirthdate = clientBirthdate;
}
}
Your hash map code will now look like:
Client newclient = new Client();
HashMap<Integer, Client> clients = new HashMap<>();
clients.put(newclient.getClientIdentifier(), newclient);
String requiredName = clients.get(scannedID).getClientName();