Java的compare比较

package com.jckb;

public class Name implements Comparable<Name>{
    private String firstName;
    private String lastName;
    
    public Name(){}
    
    public Name(String firstName, String lastName) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((firstName == null) ? 0 : firstName.hashCode());
        result = prime * result
                + ((lastName == null) ? 0 : lastName.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;
        Name other = (Name) obj;
        if (firstName == null) {
            if (other.firstName != null)
                return false;
        } else if (!firstName.equals(other.firstName))
            return false;
        if (lastName == null) {
            if (other.lastName != null)
                return false;
        } else if (!lastName.equals(other.lastName))
            return false;
        return true;
    }

    @Override
    public int compareTo(Name o) {
        int firstNameCom = this.firstName.compareTo(o.firstName);
        return (firstNameCom !=0 ? firstNameCom:this.lastName.compareTo(o.lastName));
    }

    @Override
    public String toString() {
        return firstName +"-"+lastName;
    }
    
}

//测试类
package com.jckb;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test {
    public static void main(String[] args) {

        List<Name> list = new ArrayList<Name>();
        list.add(new Name("zhang","san"));
        list.add(new Name("li","si"));
        list.add(new Name("wang","wu"));
        Collections.sort(list);
        for(Name item : list){
            System.out.println(item.toString());
        }
        
    }
}

 

 

 

posted @ 2017-02-09 21:23  郭鑫  阅读(8490)  评论(0编辑  收藏  举报