假设我有一个类:
class Node{
int count;
//提供getter/setter函数等
}
我实例化100个这样的类的对象,但count的大小是不一样的,我想对这100个对象排序,怎么做?
比如:node1中count=5,node2中count=3,node3中count=9
排序结果应该是node2<node1<node3
当然我知道排序最快用快速排序,我的意思是难道写一个快速排序的类,然后专门对这些对象的成员进行排序吗?
有没有更简单的方法?比如说接口啊(如comparable)或者一些容器(SortSet)之类的。
class Node{
int count;
//提供getter/setter函数等
}
我实例化100个这样的类的对象,但count的大小是不一样的,我想对这100个对象排序,怎么做?
比如:node1中count=5,node2中count=3,node3中count=9
排序结果应该是node2<node1<node3
当然我知道排序最快用快速排序,我的意思是难道写一个快速排序的类,然后专门对这些对象的成员进行排序吗?
有没有更简单的方法?比如说接口啊(如comparable)或者一些容器(SortSet)之类的。
import java.util.Collections;
import java.util.Comparator;
import java.util.List;class Node1 {
int count;
public Node1(int n){
this.count = n;
}
}class Node2 {
int count;
public Node2(int n){
this.count = n;
}
}class Node3 {
int count;
public Node3(int n){
this.count = n;
}
}public class CommonTest {
@SuppressWarnings("unchecked")
public static void main(String[] args){
List<Integer> list = new ArrayList<Integer>();
list.add(new Node1(3).count);
list.add(new Node2(5).count);
list.add(new Node3(1).count);
System.out.print("排序前:");
for(Integer l : list){
System.out.print( l + " ");
}
System.out.println();
Collections.sort(list);
System.out.print("排序后:");
for(Integer l : list){
System.out.print(l + " ");
}
}
}
import java.util.*;
class Node implements Comparable<Node> {
public int counter;
public Node(int n) {
counter = n;
}
public int compareTo(Node node) {
return node.counter > counter ? 1 : (node.counter < counter ? -1 : 0);
}
}
public class Test {
public static void main(String[] args) {
Set<Node> set = new TreeSet<Node>();
for(int i = 0; i < 10; i++)
set.add(new Node(i));
for(Node x : set)
System.out.println(x.counter);
}
}
import java.util.Comparator;
import java.util.Random;public class Test4 { public static void main(String[] args) {
Node[] nodes = new Node[100];
Random ran = new Random();
for (int i = 0; i < nodes.length; i++) {
nodes[i] = new Node();
nodes[i].setCount(ran.nextInt(1000));
}
Arrays.sort(nodes, new MyComparator());
for (int i = 0; i < nodes.length; i++) {
System.out.println(nodes[i].getCount());
}
}}class MyComparator implements Comparator<Node> { public int compare(Node n1, Node n2) {
return n1.getCount() - n2.getCount();
}}class Node { private int count; public int getCount() {
return count;
} public void setCount(int count) {
this.count = count;
}}