我在电话簿中有一系列条目。每个Entry对象都有三个字段。姓氏,姓名和姓名。我想按字母顺序按姓氏排序电话簿数组。我不确定最好的方法。我试图将compareTo方法用于字符串,但是如果一个姓氏是White而另一个姓氏是Smith,我不确定交换条目的最佳方法。我有一些代码,我认为只要不是第一个条目被添加到电话簿中,就可以将条目I添加到电话簿中,条目就在阵列之前。但它似乎根本没有对阵列产生任何影响。
public class Entry implements Comparable<Entry>{
String surname;
String initial;
String number;
public Entry(String surname, String initial, String number) {
this.surname = surname;
this.initial = initial;
this.number = number;
}
public String getSurname(){
return surname;
}
public String getInitial(){
return initial;
}
public String getNumber() {
return number;
}
void setNumber(String number){
this.number = number;
}
public String toString(){
return surname+ "\t " +initial+ "\t" +number;
}
public int compareTo(Entry e) {
return this.surname.compareToIgnoreCase(e.surname);
}
}
import java.util.Arrays;
public class ArrayDirectory implements Directory{
private int DIRECTORY_SIZE = 6;
Entry [] directory = new Entry[DIRECTORY_SIZE];
private int numberOfElements = 0;
public int getNumOfElements(){
return numberOfElements;
}
public void setDirectorySize(int size){
DIRECTORY_SIZE = size;
}
public int getDirectorySize(){
return DIRECTORY_SIZE;
}
public void addEntry(String surname, String initial, String num) {
// TODO add an entry to an array, also increments numberOfElements variable tracking whats in array
if(getNumOfElements() == getDirectorySize()){ // if array is full
doubleArraySize(); // put temp values into new bigger directory array
}
int i = findFreeLocation();
directory[i] = new Entry(surname, initial, num);
if( i > 0 ){
if(directory[i-1].compareTo(directory[i]) == 1){
Entry[] temp = new Entry[1];
temp[0] = directory[i-1];
directory[i-1] = directory[i];
directory[i] = temp[0];
}
}
numberOfElements++;
}