在某项目中需要使用一个集合类要求在该类集合类中使有的元素排序(集合的元素未知类型)   怎么让他升序或降序  哪位兄台有这些题发给小弟  谢谢

解决方案 »

  1.   

    先实现Comparable接口 在调用Arrays.sort()方法;
      

  2.   

    package com.xuz.csdn.june8;import java.util.Date;public class MyClass implements Comparable<MyClass> {
    private Date d; public MyClass(Date d) {
    this.setD(d);
    }

    @Override
    public String toString(){
    return "my value is " + d;
    } @Override
    public int compareTo(MyClass o) {
    if (d.after(o.getD())) {
    return -1;


    if (d.before(o.getD())) {
    return 1;
    }

    return 0;
    } public void setD(Date d) {
    this.d = d;
    } public Date getD() {
    return d;
    }
    }
      

  3.   

    package com.xuz.csdn.worldcup.day2;import java.util.SortedSet;
    import java.util.TreeSet;class Node implements Comparable<Node> {
    private String strID;

    // @Override
    // public boolean equals(Object obj) {
    // return super.equals(obj);
    // } private int iData;

    public Node(String strID,int iData){
    this.strID = strID;
    this.iData = iData;
    } public int compareTo(Node r) // 重载比较函数
    {
    if (!strID.equals(r.strID)) // 如果strID相同,则重复,需要去掉。
    {
    if (iData > r.iData)
    return -1;
    return 1;
    }
    return 0;
    } public boolean equals(Node n){
    if (this.strID.equals(n.strID)) {
    return true;
    } else {
    return false;
    }
    }

    public String toString(){
    return strID + ":" + iData;
    }

    public static void main(String[] args){
    SortedSet<Node> sNode = new TreeSet<Node>();
    sNode.add(new Node("1",1));
    sNode.add(new Node("1",2));
    sNode.add(new Node("2",1));
    sNode.add(new Node("2",1));
    for (Node node : sNode) {
    System.out.println(node);
    }
    }
    }
    这个有main方法