当前位置: 代码迷 >> J2SE >> 小弟我编写的应用TreeSet进行排序的代码
  详细解决方案

小弟我编写的应用TreeSet进行排序的代码

热度:98   发布时间:2016-04-24 00:51:54.0
我编写的应用TreeSet进行排序的代码
自己写的练习,但是不知道为什么没有任何结果,并且没有报错啊!
MyTreeSet类
Java code
package com.work;import java.util.Iterator;import java.util.TreeSet;public class MyTreeSet {    /**     * @param args     */    static TreeSet<Res> tree=new TreeSet<Res>();    MyTreeSet a=new MyTreeSet();    public static void main(String[] args) {        // TODO Auto-generated method stub       tree.add(new Res("a", 21));       tree.add(new Res("b", 19));       tree.add(new Res("c", 32));       tree.add(new Res("d", 8));           }    public void get(){        Iterator<Res> a=tree.iterator();        while (a.hasNext()) {            Res res = (Res) a.next();            System.out.println(res.getName()+"-----------"+res.getAge());        }    }}

Res类
Java code
package com.work;class Res implements Comparable<Res> {    String name;    int age;    public Res(String name, int age) {        this.name = name;        this.age = age;    }    public String getName() {        return name;    }    public int getAge() {        return age;    }    @Override    public int compareTo(Res o) {        // TODO Auto-generated method stub        if (!(o instanceof Res)) {            throw new RuntimeException();        }        if (this.age == o.age) {            return this.name.compareTo(o.name);        } else if (this.age - o.age < 0) {            return -1;        }        return 1;    }    }


------解决方案--------------------
你都没有调用输出结果的语句当然什么都没有呢哦。
------解决方案--------------------
你的程序运行了,java程序运行时从主方法 
public static void main(String[] args) {
// TODO Auto-generated method stub
tree.add(new Res("a", 21));
tree.add(new Res("b", 19));
tree.add(new Res("c", 32));
tree.add(new Res("d", 8));

}
开始的,而你的主方法只是给tree集合添加了元素而已。并没有遍历打印tree集合元素,那是应为你没有调用get()方法。当然看不到你想要的结果了。



修改方案一:
修改MyTreeSet .java中的代码为。但一般不会这样写代码。
package com.work;
import java.util.Iterator;
import java.util.TreeSet;
public class MyTreeSet {

/**
* @param args
*/
static TreeSet<Res> tree=new TreeSet<Res>();
MyTreeSet a=new MyTreeSet();
public static void main(String[] args) {
tree.add(new Res("a", 21));
tree.add(new Res("b", 19));
tree.add(new Res("c", 32));
tree.add(new Res("d", 8));
Iterator<Res> a=tree.iterator();
while (a.hasNext()) {
Res res = (Res) a.next();
System.out.println(res.getName()+"-----------"+res.getAge());
}
}
}


修改方案二:



package com.work;
import java.util.Iterator;
import java.util.TreeSet;
public class MyTreeSet {

/**
* @param args
*/
static TreeSet<Res> tree=new TreeSet<Res>();

public static void main(String[] args) {
MyTreeSet a=new MyTreeSet();
tree.add(new Res("a", 21));
tree.add(new Res("b", 19));
tree.add(new Res("c", 32));
tree.add(new Res("d", 8));
a.get();
}
public void get(){
Iterator<Res> a=tree.iterator();
while (a.hasNext()) {
Res res = (Res) a.next();
System.out.println(res.getName()+"-----------"+res.getAge());
  相关解决方案