java中类似C++的结构体排序

2 评论46次阅读2008.10.29 14:47; 作者:Felicia 

最近学习java,在网上找了挺久才找到的实现方法。
我整理了一下,下面的程序是对node类构成的数组按照dist从小到大排序。

import java.io.*;
import java.util.*;
 
class node implements Comparable {
    
public int x;
    
public int dist;
    
public node(int _x, int _dist) {
        
this.x = _x;
        
this.dist = _dist;
    
}
    
public int compareTo(Object obj) {
        
if (obj instanceof node) {
            
node b = (node) obj;
            
if (this.dist < b.dist)
                
return -1;
            
else if (this.dist > b.dist)
                
return 1;
        
}
        
return 0;
    
}
}
 
public class Main {
    
static int n;
    
static node a[];
    
public static void main(String args[]) throws Exception {
        
Scanner cin = new Scanner(System.in);
        
n = cin.nextInt();
        
a = new node[n];
        
for (int i = 0; i < n; i++) {
            
int t = cin.nextInt();
            
a[i] = new node(t, Math.abs(t));
        
}
        
Arrays.sort(a);
        
for (int i = 0; i < n; i++)
            
System.out.println(a[i].dist);
    
}
}

相关文章

  • 评论 (2)
  • 引用通告 (0)
发表评论 引用通告

  • ths | 回复 1F

    十一月 1st, 2008 at 16:00

    你好,看了你的开blog的那篇文章,然后去查看一下你的空间提供商的信息,你的空间每个月的流量是15G/月,
    请问这15G对你够用吗?会不会因此关闭你的网站? 因为我也想买个空间。

    谢谢

  • Felicia | 回复 2F

    十一月 1st, 2008 at 22:39

    我当时买的时候貌似没告诉我有流量限制啊……

暂无引用通告