接着说关于Comparator接口,
java.util Interface Comparator<T>(该泛型指定的是被比较的类),使用该接口不需要在待比较类进行比较操作,即在不修改源码的情况下进行比较(如代码交付后),
与Comparable相比稍微复杂,但是还是很方便~~
首先是待比较类,这里是一个记录温度与湿度的为了与上面做区分,在这里叫EnvironmentForms类:
public class EnvironmentForms { /**温度*/ private float temp; /**湿度*/ private float hum; public float getTemp() { return temp; } public void setTemp(float temp) { this.temp = temp; } public float getHum() { return hum; } public void setHum(float hum) { this.hum = hum; } /** * 无参构造 */ public EnvironmentForms(){} /** * 有参构造 * @param temp 温度 * @param hum 湿度 */ public EnvironmentForms(float temp, float hum) { super(); this.temp = temp; this.hum = hum; } @Override public String toString() { return "EnvironmentForm [温度=" + temp + ", 湿度=" + hum + "]\n"; } }
在不修改此类的情况下,还是对温度进行降序排列,当温度相等湿度降序排列,
首先写一个比较规则类实现Comparator接口,
实现compare int compare(T o1,T o2)与equals boolean equals(Object obj)(该方法这里没有复写),代码如下:
import java.util.Comparator; public class EnvironmentComparator implements Comparator<EnvironmentForms> { @Override public int compare(EnvironmentForms env1, EnvironmentForms env2) { //大于所给温度则返回-1 if(env1.getTemp()>env2.getTemp()){ return -1; }else if(env1.getTemp()<env2.getTemp()){ //小于所给温度返回1 return 1; }else{ //大于所给湿度返回-1 if(env1.getHum()>env2.getHum()){ return -1; //小于所给湿度返回1 }else if(env1.getTemp()<env2.getHum()){ return 1; } } return 0; } }
最后进行测试~~代码如下:
import java.util.Arrays; public class ComparatorTestMain { public static void main(String[] args) { EnvironmentForms env[] = {new EnvironmentForms(28.5f,50.1f), new EnvironmentForms(28.5f,60.1f), new EnvironmentForms(28.5f,40.1f), new EnvironmentForms(17.5f,50.1f), new EnvironmentForms(37.5f,50.1f)}; System.out.println("********排序前********"); System.out.println(Arrays.toString(env)); System.out.println("********排序后********"); Arrays.sort(env, new EnvironmentComparator()); System.out.println(Arrays.toString(env)); } }
运行结果~~
********排序前******** [EnvironmentForm [温度=28.5, 湿度=50.1] , EnvironmentForm [温度=28.5, 湿度=60.1] , EnvironmentForm [温度=28.5, 湿度=40.1] , EnvironmentForm [温度=17.5, 湿度=50.1] , EnvironmentForm [温度=37.5, 湿度=50.1] ] ********排序后******** [EnvironmentForm [温度=37.5, 湿度=50.1] , EnvironmentForm [温度=28.5, 湿度=60.1] , EnvironmentForm [温度=28.5, 湿度=50.1] , EnvironmentForm [温度=28.5, 湿度=40.1] , EnvironmentForm [温度=17.5, 湿度=50.1] ]