我在Java中有以下代码:
public class ServerInfo {
int serverId;
int serverDataRate;
public ServerInfo(int serverId, int serverDataRate) {
this.serverId = serverId;
this.serverDataRate = serverDataRate;
}
public int getServerId() {
return serverId;
}
public double getServerDataRate() {
return serverDataRate;
}
public String toString(){
return serverId + ":" + serverDataRate;
}
}
public class ServerInfoComparator implements Comparator<ServerInfo> {
@Override
public int compare(ServerInfo o1, ServerInfo o2) {
double datarate1=o1.getServerDataRate();
double datarate2=o2.getServerDataRate();
if(datarate1>datarate2)
return -1;
else if(datarate1<datarate2)
return +1;
else
return 0;
}
}
public class Sample {
List<ServerInfo> listOfServers= new ArrayList<ServerInfo>();
public void insertIntoList(){
listOfServers.add( new ServerInfo(0,256));
listOfServers.add( new ServerInfo(1,270));
listOfServers.add( new ServerInfo(2,256));
listOfServers.add( new ServerInfo(3,290));
listOfServers.add( new ServerInfo(4,300));
listOfServers.add( new ServerInfo(5,300));
listOfServers.add( new ServerInfo(6,256));
listOfServers.add( new ServerInfo(7,265));
listOfServers.add( new ServerInfo(8,289));
listOfServers.add( new ServerInfo(9,310));
}
public static void main( String[] args){
Sample s = new Sample();
s.insertIntoList();
ServerInfoComparator com = new ServerInfoComparator();
Collections.sort(s.listOfServers,com);
for( ServerInfo server: s.listOfServers){
System.out.println(server);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我使用上面的代码基于serverDataRate按降序对元素进行排序.假设我在列表中有100个元素的更大样本集,并且代码必须每5-10秒执行一次,那么样本集非常小.这是对列表进行排序的最快方法还是有一种我不知道的更快的方法?
Pet*_*rey 12
我改变了你的考试
private final List<ServerInfo> listOfServers = new ArrayList<ServerInfo>();
public void insertIntoList() {
for (int i = 0; i < 1000000; i++)
listOfServers.add(new ServerInfo(i, (int) (200 + Math.random() * 200)));
}
public static void main(String[] args) {
MyApp s = new MyApp();
s.insertIntoList();
ServerInfoComparator com = new ServerInfoComparator();
long start = System.nanoTime();
Collections.sort(s.listOfServers, com);
long time = System.nanoTime() - start;
System.out.printf("Sorting %,d took %.3f seconds%n", s.listOfServers.size(), time/1e9);
for (ServerInfo server : s.listOfServers) {
// System.out.println(server);
}
}
Run Code Online (Sandbox Code Playgroud)
它打印出来
Sorting 1,000,000 took 0.438 seconds
Run Code Online (Sandbox Code Playgroud)
那要快一点;)
顺便说一句:我改变了double字段int.