当前位置:编程学习 > JAVA >>

java例程练习(Comparable接口)

import java.lang.Comparable; 
import java.util.List; 
import java.util.LinkedList; 
import java.util.Collections; 
 
public class TestCompareTo { 
 
    public static void main(String[] args) { 
        List l1 = new LinkedList(); 
         
        l1.add(new Name("Karl", "M")); 
        l1.add(new Name("Stever", "Lee")); 
        l1.add(new Name("John", "O")); 
        l1.add(new Name("Tom", "M")); 
         
        System.out.println(l1); 
         
        Collections.sort(l1); 
        System.out.println(l1); 
             
    } 

 
class Name implements Comparable{ 
    private String firstName; 
    private String lastName; 
     
    Name(String firstName, String lastName) { 
        this.setFirstName(firstName); 
        this.setLastName(lastName); 
    } 
     
    public void setFirstName(String firstName) { 
        this.firstName = firstName; 
    } 
     
    public String getFirstName() { 
        return firstName; 
    } 
     
    public void setLastName(String lastName) { 
        this.lastName = lastName; 
    } 
     
    public String getLastName() { 
        return lastName; 
    } 
     
    public String toString() { 
        return firstName + " " + lastName; 
    } 
     
    public boolean equals(Object obj) { 
        if(obj instanceof Name) { 
            Name name = (Name) obj; 
            return (firstName.equals(name.firstName)) &&  
                   (lastName.equals(name.lastName)); 
        } 
        return super.equals(obj); 
    } 
     
    public int hashCode() { 
        return firstName.hashCode(); 
    } 
     
    public int compareTo(Object o) { 
        Name n = (Name) o; 
        int lastCmp = lastName.compareTo(n.lastName); 
        return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName)); 
    } 
     

 


摘自 Yours风之恋

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,