So you asked about labelling (and by extension sorting), but refer to uniquely identifying - here is an answer to both :)
For Sorting
Real life programs deal with that every day, just ensure your comparable code by default sorts by 2 attributes
- LastName
- FirstName
If they compare in that order, you should end up with:
XavierAllen
JayReese
BillySmith
ClaraSmith
JohnSmith
To compare multiple attributes, I would refer you to this stackoverflow topic, which shows how to do both single and multiple comparisons on a Person object with the same field names even ; )
How to compare objects by multiple fields
For Unique Referance
Also, if you were concerned about uniquely identifying the Person outside of simple comparison sorting, then you would add an int field (or guid, or whatever your flavour) that would hold a unique value
Basically same as a Database PK - you would never use a persons name as a PK in a database, so your Person ideally should have a property like that too.
If you wanted to add this PK to your toString() then go for it
import java.util.*;
public class Person implements Comparable<Person> {
private int personID;
private String firstName;
private String lastName;
public Person(String firstName, String lastName, int personID) {
this.firstName = firstName;
this.lastName = lastName;
this.personID = personID;
}
public int getID(){
return this.personID;
}
public String toString() {
return this.personID + ": " + this.lastName + ", " + this.firstName;
}
}
@Mshnik did post a method for dynamically adding PK, but youd be much better off checking the Person collection or some high level variable to find the last personID and go from there - else that dynamic value can only be used in the most limited of contexts, and you may as well just use the index its located at in the Person collection you are retrieving it from