나는라는 클래스가 Word
각 인스턴스가 가지고있는 String
, ArrayList<Character>
그리고를 double
. 의이 클래스의 3 개 인스턴스가 있다고 가정 해 봅시다. 나는 새로운 만들고 싶습니다 ArrayList<String>
3 개 단어 문자열이 포함 된합니다. 그러나, 문자열의 순서는 원래 인스턴스에서 두 배의 낮은 높이에서 이동해야합니다. 이 프로젝트의 주요 규정이 있다는 것입니다 Collections.sort
방법은 사용할 수 없습니다. 아래의 코드를보고이 루프를 작성하는 방법을 생각할 수있는 경우에 저를 (실제로는 50,000 단어가 있기 때문에 루프가 필요) 알려 주시기 바랍니다 :
import java.awt.List;
import java.util.ArrayList;
import java.util.Arrays;
public class WordRecommender {
String fileName;
public WordRecommender(String fileName) {
this.fileName = fileName;
}
public static void main(String[] args) {
ArrayList<Word> objectArray = new ArrayList<Word>();
objectArray.add(new Word("people", null ,0.8));
objectArray.add(new Word("dogs", null ,0.4));
objectArray.add(new Word("cats", null ,0.6));
ArrayList<String> outputArray = new ArrayList<String>();
for (int i = 0; i < finalArray.size(); i++) {
// code here to find the value of each double and place the
// associated strings into output Array from highest to lowest
}
// ideal outputArray order = ["people", "cats", "dogs"]
}
import java.util.ArrayList;
public class Word {
String wordName;
ArrayList<Character> uniqueLetters;
double percent;
public Word(String string, double percent) {
ArrayList<Character> tempArray = new ArrayList<Character>();
for (int i = 0; i < string.length(); i++) {
tempArray.add(string.charAt(i));
}
this.wordName = string;
this.uniqueLetters = tempArray;
this.percent = percent;
}
}
는 2 중요한 단계로 나눌 수 있습니다 달성하는 데 필요한 결과 :
- 2 개주는 방법을 설명하는
Word
그 어떤이의 다른 전에 넣어 될 것이다들List
- 실제로 종류의 목록에 비교 방법을 사용하여
Word
의.
1 단계 : 어떻게 우리가 처음 오는 단어를 결정할 수 있습니다?
자바라는 인터페이스를 가지고 있습니다 Comparable
. 이름은 별다른 설명이다. 당신이 당신이 인터페이스를 구현할 때 Word
클래스,이 클래스의 인스턴스가 서로 비교 될 수있는 자바를 말하고있다.
public class Word implements Comparable<Word>{
당신이 당신이 라인을 편집 할 때 Word
클래스, 당신의 IDE는 아마 "실종에 대해 불평 compareTo()
방법". compareTo()
방법이 정의되어 Comparable
인터페이스와 작업 하나 고려해야 2 개 인스턴스에서, 결정은 "큰"(또는 우리의 경우에는 먼저 넣고한다 List
).
사용법의 예는 다음과 같습니다 "apple".compareTo("banana");
. 이 메소드 호출은 동일한 "값"에있는 첫번째 인스턴스 ( "애플") "큰"이면 번째 인스턴스 ( "바나나")은 "큰"이면 음수를 양수 반환 제로 두 경우해야 . 그런데, compareTo()
구현 방법 String
자바의 알파벳 순서에 따라 인스턴스를 평가합니다.
그래서는 우리의 버전을 구현할 수 있도록 compareTo()
우리를위한 방법 Word
클래스를.
@Override
public int compareTo(Word anotherWord) {
if(this.percent > anotherWord.percent) {
return 1;
} else if (this.percent < anotherWord.percent) {
return -1;
} else {
return 0;
}
}
첫 번째 인스턴스가 두 번째보다 큰 경우이 구현은 양의 값을 반환한다는 것을 명심하고, 주변에 다른 방법으로 음의 값.
이제 우리는 우리를 비교하는 방법을 가지고 Words
, 우리는 정렬 부분에 이동할 수 있습니다.
2 단계 : 정렬 알고리즘
인터넷에서 사용할 수 정렬 알고리즘의 거대한 다양성이있다. 일부는 일부는 구현하기 쉽게, 덜 효율적이다. 당신은 그들 중 일부를 연구 할 수 있습니다 여기에 .
나를 위해, 가장 쉬운 정렬 알고리즘이라고 거품 정렬 . 그것은하지만, 매우 효율적이지 않습니다.
ArrayList<Word> objectArray = new ArrayList<Word>();
objectArray.add(new Word("people", 0.8));
objectArray.add(new Word("dogs", 0.4));
objectArray.add(new Word("cats", 0.6));
for(int i = 0; i < objectArray.size() - 1; i++) {
for(int j = 0; j < objectArray.size() - i - 1; j++) {
// Remember: a compareTo() call returning a negative number
// means that the first instance is smaller than the second.
if(objectArray.get(j).compareTo(objectArray.get(j + 1)) < 0) {
Word auxiliary = objectArray.get(j);
objectArray.set(j, objectArray.get(j + 1));
objectArray.set(j + 1, auxiliary);
}
}
}
이 두 개의 중첩 for
루프 정렬합니다 objectArray
내림차순으로 percent
.