효율적으로 검색하고 싶은 객체 배열 (전화 번호부 항목은 Entry(surname,initials,extension)
양식으로 저장 됨)이 있습니다. 이렇게하려면 Arrays.binarySearch()
을 사용하려고합니다. 하나는 이름을 사용하고 다른 하나는 숫자를 사용하여 배열을 검색하는 두 가지 별도의 메소드가 있습니다. 내 addEntry()
메서드에서 올바른 위치에 각 요소를 삽입 할 때 배열은 알파벳순으로 성으로 정렬됩니다. 배열을 알파벳 순서로 정렬 할 때 binarySearch()
을 이름으로 검색 할 때 사용할 수는 있지만 숫자로 검색 할 때 배열은 정렬되지 않습니다. 성을 비교하기 위해 내 항목 클래스에서 compareTo()
을 재정의했습니다. 그러나 숫자로 검색 할 때 배열을 숫자의 오름차순으로 정렬해야하는데 어떻게해야할지 모르겠습니다.바이너리 검색 배열 정렬
public int lookupNumberByName(String surname, String initials) {
int index = 0;
if (countElements() == directory.length) {
Entry lookup = new Entry(surname, initials);
index = Arrays.binarySearch(directory, lookup);
}
else if (countElements() != directory.length) {
Entry[] origArray = directory;
Entry[] cutArray = Arrays
.copyOfRange(directory, 0, countElements());
directory = cutArray;
Entry lookup = new Entry(surname, initials);
index = Arrays.binarySearch(directory, lookup);
directory = origArray;
}
return index;
}
내
LookupByNumber()
방법이 그런 짓을하고 싶은
-
public int LookupByNumber(int extension) {
Entry[] origArray1 = directory;
Entry[] cutArray1 = Arrays.copyOfRange(directory, 0, countElements());
directory = cutArray1;
Arrays.sort(directory); //sort in ascending order of numbers
Entry lookup1 = new Entry(extension);
int index1 = Arrays.binarySearch(directory, lookup1);
String surname1 = directory[index1].getSurname();
String initals1 = directory[index1].getInitials();
directory = origArray1;
int arrayPos = lookupNumberByName(surname1,initials1);
return arrayPos;
내 compareTo
방법 - 나는 실현 - 매우
편집 감사
public int compareTo(Entry other) {
return this.surname.compareTo(other.getSurname());
}
도움말 배열이 이에 대한 최상의 데이터 구조는 아니지만, 내가 이 작업을 위해 배열을 사용하도록 특별히 요청 받았습니다.
업데이트 - 정확히 sort(T[] a, Comparator<? super T> c)
은 어떻게 작동합니까? 내가 기록하려고 할 때 내 자신의 Comparator
-
public class numberSorter implements Comparator<Entry> {
@Override
public int compare(Entry o1, Entry o2) {
if (o1.getExtension() > o2.getExtension()) {
return 1;
}
if (o1.getExtension() == o2.getExtension()) {
return 0;
}
if (o1.getExtension() < o2.getExtension()) {
return -1;
}
return -1;
}
}
그리고 나는 다음과 같은 예외가 Arrays.sort(directory,new numberSorter());
를 호출 -
java.lang.NullPointerException
at java.lang.String.compareTo(Unknown Source)
at project.Entry.compareTo(Entry.java:45)
at project.Entry.compareTo(Entry.java:1)
at java.util.Arrays.binarySearch0(Unknown Source)
at java.util.Arrays.binarySearch(Unknown Source)
at project.ArrayDirectory.LookupByNumber(ArrayDirectory.java:128)
at project.test.main(test.java:29)
정확히 내가 잘못 뭐하는 거지
?