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

来源:互联网 发布:看星空的软件 编辑:程序博客网 时间:2024/06/07 01:16

和C++类似,写一个Comparable。

下面的程序是对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);//按compareTo方法排序        for (int i = 0; i < n; i++)            System.out.println(a[i].dist);    }}


原创粉丝点击