如何区分this.age 和 student.age

somedaywx 2012-10-09 02:57:13
package test;

import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;

public class StudentForSet implements Comparable{
private String name;
private int age;

public StudentForSet(String name, int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "name:"+name+" "+"age:"+age;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SortedSet set = new TreeSet();
set.add(new StudentForSet("eiok",23)); //行10
set.add(new StudentForSet("zhangsan",21));//行11
set.add(new StudentForSet("wangwu",24));//行12
set.add(new StudentForSet("bak",25));//行13
Iterator it = set.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
@Override
public int compareTo(Object obj) {
// TODO Auto-generated method stub
StudentForSet student = (StudentForSet) obj;//将参数对象强转成当前类类型
return this.age-student.age;
}
为了更好理解compareTo这个重写的方法,求高手解释下this.age 和 student.age
}
...全文
311 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
lzh_me 2012-10-09
  • 打赏
  • 举报
回复
要理解对象的含义,不同的对象就好比不同的人,你的年龄和他的年龄是不一样的,虽然都叫做“age”,同时还要理解,java里面的参数传递都是值传递。你的age和他的age里面的值是不一样的。
liangtu 2012-10-09
  • 打赏
  • 举报
回复
这个比较的过程是SortedSet自己处理的,类似冒泡排序的的两两进行比较。

somedaywx 2012-10-09
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 的回复:]

this.age-student.age;

在上面的代码中,int result = sf1.compareTo(sf2);
this.age 就相当于 sf1.age,
student.age 相当于 sf2.age

如果反过来sf2.compareTo(sf1);
那么this.age 就相当于 sf2.age,
student.age 相当于 sf1.age
[/Quote]

你说的这些我都清楚,只是我不明白,当调用new StudentForSet("eiok",23),this肯定就是当前对象啦,那么StudentForSet student = (StudentForSet) obj;是怎么把new StudentForSet("zhangsan",21)这个对象传给obj的,然后进行比较。
huimiezu 2012-10-09
  • 打赏
  • 举报
回复
this指当前对象
liangtu 2012-10-09
  • 打赏
  • 举报
回复
this.age-student.age;

在上面的代码中,int result = sf1.compareTo(sf2);
this.age 就相当于 sf1.age,
student.age 相当于 sf2.age

如果反过来sf2.compareTo(sf1);
那么this.age 就相当于 sf2.age,
student.age 相当于 sf1.age

liangtu 2012-10-09
  • 打赏
  • 举报
回复
SortedSet是一个按照元素递增排序的集合,根据compareTo方法排序。StudentForSet类改写了compareTo方法,因此会按照改写的方法进行排序。

compareTo方法是对两个对象进行比较,在这里是对两个StudentForSet对象进行比较,可以通过以下代码理解:

StudentForSet sf1 = new StudentForSet("eiok", 23);
StudentForSet sf2 = new StudentForSet("zhangsan", 21);
int result = sf1.compareTo(sf2);
if (result > 0) {
System.out.println(" sf1 大于sf2");
} else if (result == 0) {
System.out.println(" sf1 等于sf2");
} else {
System.out.println(" sf1 小于sf2");
}



somedaywx 2012-10-09
  • 打赏
  • 举报
回复
输出结果为:
name:zhangsan age:21
name:eiok age:23
name:wangwu age:24
name:bak age:25

67,515

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧