2011-12-08 33 views
0

我有一個java人反對:通過日期,比較對象(實現比較)

public class People { 

     String lastname; 
     String firstname; 
     String gender; 
     String datebirth; 
     String fcolor; 

     public People(String lastname, String firstname, String gender,String datebirth, String fcolor) { 
       this.lastname = lastname; 
       this.firstname = firstname; 
       this.gender = gender; 
       this.datebirth = datebirth; 
       this.fcolor = fcolor; 
     } 
     public String getLastname() { 
       return lastname; 
     } 
     public String getFirstname() { 
       return firstname; 
     } 
     public String getGender() { 
       return gender; 
     } 
     public String getFcolor() { 
       return fcolor; 
     } 
     public String getDatebirth() { 
       return datebirth; 
     }   
} 

我想建立一個比較器通過datebirth比較(datebirth有時這種格式的「1943年2月13日」,有時這種格式的「1943年2月13日」,你能幫助我如何實現它

我開始,但是糊塗了:

import java.util.Date; 
import java.text.SimpleDateFormat; 
import java.util.Comparator; 
import java.text.DateFormat; 

public class CompareDateBirth implements Comparator<People>{ 

     public int compare(People p, People q) { 

       DateFormat df = new SimpleDateFormat("dd-MM-yyyy"); 
       Date Pdate = null; 
       Date Qdate= null; 
        try { 
        Pdate = df.parse(p.getDatebirth()); 
        Qdate = df.parse(q.getDatebirth()); 
        } catch (Exception e) { 
        e.printStackTrace(); 
        }  
         return Pdate.compareTo(Qdate) > 0 ? 1 : 0; 
     } 
} 

回答

9

如果您想使用存儲出生日期的正確的類型 - java.util.Date個對象而不是String - 你不會有這個問題。格式化是一個顯示問題。

一個名爲「People」的類?

這裏是我怎麼可能做到這一點(下面的所有類單獨.java文件名爲模型包):

package model; 

public enum Gender { MALE, FEMALE } 

public class Person { 
    private String firstName; 
    private String lastName; 
    private Gender gender; 
    private Date birthDate; // I'd make sure to set hh:mm:ss all to midnight 

    // constructors, getters, equals, hashCode, and toString are left for you 
} 

public class BirthDateComparator implements Comparator<Person> { 
    public int compare(Person p, Person q) { 
     if (p.getBirthDate().before(q.getBirthDate()) { 
      return -1; 
     } else if (p.getBirthDate().after(q.getBirthDate()) { 
      return 1; 
     } else { 
      return 0; 
     }   
    } 
} 
+0

非常感謝您的幫助。我想現在有一個比較器,比較性別(女性在男性之前),然後姓氏升序,謝謝你的幫助表示讚賞。 – akram

+0

警告,p或q可能爲空。 – Nico

+0

五年來不及。當然,OP應該檢查所有這些。它只是作爲一個例子,而不是生產代碼。 – duffymo

1

我建議保存在Java代碼中的日期作爲一項長期的具有UNIX時間那一天,它在各個平臺上更可靠。你也可以使用分隔符手動分割日期,所以如果有' - '那麼這是你的分隔符,否則如果存在'/',那麼你使用它來分割。

這樣你就可以提取日,月和年並構建日期對象。

-1
Public class BirthDateComparator implements java.util.Comparator<Person> { 
    public int compare(Person p1, Person p2) { 
     return p1.getBirthDate().compareTo(p2.getBirthDate()); 
    } 
} 
+0

警告p1或p2可能爲空 – Nico