Java 自定义类数组,和比较器;
Comparator 实现
import java.util.*;
public class Main{
static class Node{
int v;
Node(){
this.v = 0;
}
Node(int v){
this.v = v;
}
}
public static void main(String[] args){
Node[] ddd = new Node[3];
Arrays.fill(ddd,new Node());
ddd[0] = new Node(1);
ddd[1] = new Node(2);
ddd[2] = new Node(3);
Arrays.sort(ddd, 0,3,new Comparator<Node>(){
public int compare(Node a, Node b){
return b.v - a.v;}
});//自定义比较器,return 大于零这表示要交换;
System.out.println(ddd[2].v);
}
}
结果为1;
Comparable实现
import java.util.*;
public class Main{
static class Node implements Comparable<Node>{
int v;
Node(){
this.v = 0;
}
Node(int v){
this.v = v;
}
public int compareTo(Node node){
return node.v - v;
}
}
static int[] prior = new int[100002];
public static void main(String[] args){
Node[] ddd = new Node[3];
Arrays.fill(ddd,new Node());
ddd[0] = new Node(1);
ddd[1] = new Node(2);
ddd[2] = new Node(3);
Arrays.sort(ddd, 0,3/*,new Comparator<Node>(){
public int compare(Node a, Node b){
return b.v - a.v;}
}*/);
System.out.println(ddd[2].v);
}
}
结果为1;