【Java】实现Comparable和Comparator接口对数组和集合进行排序
数组排序
原数组:
String[] words = {"xbc","pcxbcf","xb","cxbc","pcxbc"};
Arrays.sort(Object[] a)
使用的条件是数组元素类型要实现Comparable接口,然后该方法就能按照重写的compareTo方法进行排序。
String类型的compareTo方法:
public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}
进行排序并打印结果:
Arrays.sort(words);
for(int i = 0 ; i < words.length; i++) {
System.out.print(words[i] + ",");
}
因为String的compareTo方法是比较ascii码值,所以是按大小写排序,排序结果如下:
cxbc,pcxbc,pcxbcf,xb,xbc,
Arrays.sort(T[] a, Comparator<? super T> cmp)
使用的条件是自定义一个Comparator的实现类,然后该方法就能按照重写的compare方法进行排序。
我们自定义一个比较字符串长度的Comparator:
public class StringLengthComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
}
进行排序并打印结果:
Arrays.sort(words, new StringLengthComparator());
for(int i = 0 ; i < words.length; i++) {
System.out.print(words[i] + ",");
}
结果按照字符串长度排序:
xb,xbc,cxbc,pcxbc,pcxbcf,
集合排序
Collections.sort(List list)
使用的条件是T要实现Comparable接口,然后该方法就能按照重写的compareTo方法进行排序。
Collections.sort(List list, Comparator<? super T> c)
使用的条件是自定义一个Comparator的实现类,然后该方法就能按照重写的compare方法进行排序。
List.sort(Comparator<? super E> c)
用法同Collections.sort
思想和数组是一样的,这里我们把words转为List,用这几个方法排序并打印结果:
String[] words = {"xbc","pcxbcf","xb","cxbc","pcxbc"};
List<String> list = Arrays.asList(words);
for(int i = 0 ; i < list.size(); i++) {
System.out.print(list.get(i) + ",");
}
System.out.println("\n");
Collections.sort(list);
for(int i = 0 ; i < list.size(); i++) {
System.out.print(list.get(i) + ",");
}
System.out.println("\n");
Collections.sort(list, new StringLengthComparator());
for(int i = 0 ; i < list.size(); i++) {
System.out.print(list.get(i) + ",");
}
xbc,pcxbcf,xb,cxbc,pcxbc,
cxbc,pcxbc,pcxbcf,xb,xbc,
xb,xbc,cxbc,pcxbc,pcxbcf,
转换
Arrays.sort的参数必须是数组,Collections.sort的参数必须是List,所以想得到其它类型容器的排序结果需要先将它们转为数组或List再排序。
数组转List
可以用Arrays.asList(零散同类型对象/数组)
String[] words = {"xbc","pcxbcf","xb","cxbc","pcxbc"};
List<String> list = Arrays.asList(words);
Set转List
可以用new ArrayList<>(set)
Set<String> set = new HashSet<>();
List<String> list = new ArrayList<>(set);
List,Set转数组
可以用Collection.toArray()
String[] words1 = (String[]) set.toArray();
String[] words2 = (String[]) list.toArray();
|