一段代码问题
各位大虾,帮忙看下下面的代码,运行结果为
SYL.Students@525483cd
SYL.Students@2a9931f5
SYL.Students@2f9ee1ac
SYL.Students@67f1fba0
这好像不对,但看不出错在了那里;另外请看懂的麻烦在关键处加个注释。
package SYL;
import java.util.*;
public class TreeSetTest {
/**
* @param args
*/
public static void main(String[] args)
{
TreeSet ts = new TreeSet(new Students.compareToStudent());
ts.add(new Students(2,"shangsan"));
ts.add(new Students(3,"lishi"));
ts.add(new Students(1,"wangwu"));
ts.add(new Students(4,"maliu"));
Iterator it = ts.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
class Students implements Comparable
{
int num;
String name;
Students(int num,String name)
{
this.num = num;
this.name = name;
}
static class compareToStudent implements Comparator{
public int compare(Object o1,Object o2){
Students s1 = (Students)o1;
Students s2 = (Students)o2;
int rulst = s1.num > s2.num ? 1 : (s1.num==s2.num ? 0:-1);
if(rulst==0)
{
rulst = s1.name.compareTo(s2.name);
}
return rulst;
}
}
public int compareTo(Object o)
{
int result;
Students s = (Students)o;
result = num > s.num ? 1:(num == s.num ? 0:-1);
if(result == 0)
{
result = name.compareTo(s.name);
}
return result;
}
public String toSting()
{
return num+":"+name;
}
}
------解决方案--------------------class Students implements Comparable
{
int num;
String name;
Students(int num,String name)
{
this.num = num;
this.name = name;
}
public String toSting()
{
return "num:"+num+",name:"+name
}
------解决方案--------------------把toString方法写到学生类里
对象的默认输出是对象+@+对象所对应的散列值 重写了toString方法后可以按照自己的想法输出
------解决方案--------------------oh my god!
.............
public String toSting()
{
return num+":"+name;
}
=>
public String toString()
{
return num+":"+name;
}
------解决方案--------------------应该是你使用了Iterator,会产生警告
------解决方案--------------------import java.util.*;
public class TreeSetTest {
/**
* @param args
*/
public static void main(String[] args)
{
TreeSet ts = new TreeSet(new Students.compareToStudent());
ts.add(new Students(2,"shangsan"));
ts.add(new Students(3,"lishi"));
ts.add(new Students(1,"wangwu"));
ts.add(new Students(4,"maliu"));
Iterator it = ts.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
class Students implements Comparable
{
int num;
String name;
Students(int num,String name)
{
this.num = num;
this.name = name;
}
static class compareToStudent implements Comparator{
public int compare(Object o1,Object o2){
Students s1 = (Students)o1;
Students s2 = (Students)o2;
int rulst = s1.num > s2.num ? 1 : (s1.num==s2.num ? 0:-1);