class R implements Comparable
{
int count;
public R(int count)
{
this.count = count;
}
public boolean equals(Object obj)
{
if (obj instanceof R)
{
R r = (R)obj;
if (r.count == this.count) //1.这里的r.count与this.count分别代表什么
{ //2.如何通过equal()方法比较R(5) R(-3) R(9) R(-2)
return true;
}
}
return false;
}
public int compareTo(Object obj)
{
R r = (R)obj;
if (this.count > r.count) //1.这里的r.count与this.count分别代表什么
{
return 1; //2.如何通过equal()方法比较R(5) R(-3) R(9) R(-2)
}
else if (this.count == r.count)
{
return 0;
}
else
{
return -1;
}
}
}
public class TestTreeSet2
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
ts.add(new R(5));
ts.add(new R(-3));
ts.add(new R(9));
ts.add(new R(-2));
}
}问题见代码过程 刚刚接触JAVA 求解 在线等。
{
int count;
public R(int count)
{
this.count = count;
}
public boolean equals(Object obj)
{
if (obj instanceof R)
{
R r = (R)obj;
if (r.count == this.count) //1.这里的r.count与this.count分别代表什么
{ //2.如何通过equal()方法比较R(5) R(-3) R(9) R(-2)
return true;
}
}
return false;
}
public int compareTo(Object obj)
{
R r = (R)obj;
if (this.count > r.count) //1.这里的r.count与this.count分别代表什么
{
return 1; //2.如何通过equal()方法比较R(5) R(-3) R(9) R(-2)
}
else if (this.count == r.count)
{
return 0;
}
else
{
return -1;
}
}
}
public class TestTreeSet2
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
ts.add(new R(5));
ts.add(new R(-3));
ts.add(new R(9));
ts.add(new R(-2));
}
}问题见代码过程 刚刚接触JAVA 求解 在线等。
例如:R r1=new R(5); R r2=new R(2);
r1.equals(r2); //r1就是this2.调用equals方法见(1)
调用compareTo方法:
R r1=new R(5);
r1.compareTo(2); //不必先将2作为参数实例化r2
this作为java的一个关键指的就是本类。你可以看到在你的R类中出现了this那么这个this就代表R类。
另外你重写了compareTo方法。而在main方法里你用的是TreeSet 这个集合,而存在这个集合中的数据是有序的。也就是通过你的compareTo方法来排序。
如果你有arrayList就不存在这个问题了。尽管你写了compareTo方法也不会调用的,因为无序嘛!
equals()方法是Object类中的方法,每个类到是Object子类,这里是重写(override)这个方法。
它们都有各自的意义。
有一个Comparator类与Comparable是很相似的,里面有一个compare()方法。