I want to alphabetically order entries into an ArrayList directory called entries. I want as a new entry is added to the directory to be placed into an appropriate position in the ArrayList.
For example, if we have two entries already in the directory with surnames: "Beta" and "Cee" and we want to add a new entry that has surname: "Alpha", "Alpha" should be placed first.
My question is, How can I overwrite the compareTo method to compare the two strings (String "one", and the other String that is passed into the method-"surname") alphabetically?
private ArrayList<Entry> entries=new ArrayList<>();
public void addEntry(String surname, String initial, String number) {
Entry entry=new Entry(surname,initial,number);
if (surname == null || initial == null || number == null)
throw new IllegalArgumentException("Please fill all the required fields, [surname,initials,number]");
else {
boolean flag = false;
for (int x = 0; x < entries.size(); x++) {
String one= entries.get(x).getSurname();
if (one.compareTo(surname)>0) {
entries.add(x,entry);
flag = true;
break;
}
}
if (!flag) {
entries.add(entry);
}
}
}
In my opinion ArrayList
is not a right choice for this situation, you seem to add the new Entry
in the "correct" position according to the compareTo
method defined in the Entry
class.
So ideally a TreeSet
should be used which basically maintains the ordering of the elements based on the compareTo
defined in the Entry
class which is the "default ordering".
class Entry implements Comparable<Entry>{
private String surname;
private String initial;
private String number;
Entry(String surname, String initial, String number){
this.surname = surname;
this.number =number;
this.initial = initial;
}
@Override
public int compareTo(Entry entry){
return this.surname.compareTo(entry.surname);
}
}
And the addEntry
method should be simply:
private Set<Entry> entries = new TreeSet<>();
public void addEntry(String surname, String initial, String number) {
if (surname == null || initial == null || number == null)
throw new IllegalArgumentException("Please fill all the required fields, [surname,initials,number]");
else {
Entry entry=new Entry(surname,initial,number);
entries.add(entry);
}
}
And if you really need an List
, you can simply wrap the TreeSet
instance in the ArrayList
constructor:
List<Entry> list = new ArrayList(entries);