本帖最后由 librazeng 于 2013-5-24 08:18 编辑
在玩集合的时候,发现不明白为什么类中覆写了equals和comparaTo方法,添加到集合中就能自动排序了。
这是为什么呀,添加的时候,上一个元素和下一个元素是怎么比较的啊?
自己写的代码,有点看不懂了。- public class Person extends Object implements Comparable<Person>{
- /**
- * @param args
- */
- private String name;
- private int 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 int compareTo(Person p){
- int temp=this.name.compareTo(p.name);
- return temp==0?this.age-p.age:temp;
- }
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + age;
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- return result;
- }
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- Person other = (Person) obj;
- if (age != other.age)
- return false;
- if (name == null) {
- if (other.name != null)
- return false;
- } else if (!name.equals(other.name))
- return false;
- return true;
- }
- public Person() {
- super();
- }
- public Person(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- }
复制代码- public class GenericAdvanceDemo {
- /**
- *
- * @param args
- */
- public static void main(String[] args) {
- TreeSet<Person> ts=new TreeSet<Person>();//new ComparatorByName()
- ts.add(new Person("xiaotao",20));
- ts.add(new Person("taoran",19));
- ts.add(new Person("wangtaoran",18));
- ts.add(new Person("anneng",25));
- ts.add(new Person("haoyuan",20));
- ts.add(new Person("haoyuan",20)); //添加进入后,元素之间是怎么比较的啊??
- for(Iterator<Person> it=ts.iterator();it.hasNext();){
- Person p=it.next();
- System.out.println(p.getName()+p.getAge());
- }
复制代码 谢谢各位!
|