1 19 20 package org.netbeans.modules.editor.completion; 21 22 import java.util.Comparator ; 23 import org.netbeans.spi.editor.completion.CompletionItem; 24 import org.netbeans.spi.editor.completion.CompletionResultSet; 25 26 31 32 public class CompletionItemComparator implements Comparator <CompletionItem> { 33 34 public static final Comparator <CompletionItem> BY_PRIORITY = new CompletionItemComparator(true); 35 36 public static final Comparator <CompletionItem> ALPHABETICAL = new CompletionItemComparator(false); 37 38 private final boolean byPriority; 39 40 private CompletionItemComparator(boolean byPriority) { 41 this.byPriority = byPriority; 42 } 43 44 public static final Comparator <CompletionItem> get(int sortType) { 45 if (sortType == CompletionResultSet.PRIORITY_SORT_TYPE) 46 return BY_PRIORITY; 47 if (sortType == CompletionResultSet.TEXT_SORT_TYPE) 48 return ALPHABETICAL; 49 throw new IllegalArgumentException (); 50 } 51 52 public int compare(CompletionItem i1, CompletionItem i2) { 53 if (i1 == i2) 54 return 0; 55 if (byPriority) { 56 int importanceDiff = i1.getSortPriority() - i2.getSortPriority(); 57 if (importanceDiff != 0) 58 return importanceDiff; 59 int alphabeticalDiff = compareText(i1.getSortText(), i2.getSortText()); 60 if (alphabeticalDiff != 0) 61 return alphabeticalDiff; 62 } else { 63 int alphabeticalDiff = compareText(i1.getSortText(), i2.getSortText()); 64 if (alphabeticalDiff != 0) 65 return alphabeticalDiff; 66 int importanceDiff = i1.getSortPriority() - i2.getSortPriority(); 67 if (importanceDiff != 0) 68 return importanceDiff; 69 } 70 return -1; 71 } 72 73 private static int compareText(CharSequence text1, CharSequence text2) { 74 int len = Math.min(text1.length(), text2.length()); 75 for (int i = 0; i < len; i++) { 76 char ch1 = text1.charAt(i); 77 char ch2 = text2.charAt(i); 78 if (ch1 != ch2) { 79 return ch1 - ch2; 80 } 81 } 82 return text1.length() - text2.length(); 83 } 84 85 } 86 | Popular Tags |