簡體   English   中英

Object類型的數組,並比較數組中的對象

[英]Array of type Object, and comparing the objects inside the array

我正在創建一個Object類型的數組。 我有兩個不同的類,Employee和Person,它們具有簡單的屬性,如姓名,薪水(員工)名字,出生日期(人)。 我需要在我的數組中添加一些Employee和Person對象,並比較數組中的某些內容。 例如,從數組中檢索最年輕的Person。

public class Driver {

public static void main(String[] args) {
    Employee e1 = new Employee("Den", 2000);

    Employee e2 = new Employee("Jon", 1004);

    Person p1 = new Person("Pen", "Tel", "1993");
    Person p2 = new Person("Jon", "Smith", "1933");

    Object [] crr;
    crr = new Object[4];
    crr[0] = e1;
    crr[1] = p1;
    crr[2] = p2;
    crr[3] = e2;
    System.out.println();
    new Driver().printObjectArray("array crr", crr);

}
public void printObjectArray(String arrayName, Object [] array){
    for (int i = 0; i < array.length; i++){
        System.out.println(arrayName + "["+ i +"]" + array[i].toString());
    }
    System.out.println("--------------------");
}   
}

我如何比較陣列上的某些東西。 就像打印最年輕的人一樣,這意味着我必須查看數組並查看它是否為Person對象,然后對這些對象進行getDateOfBirth並打印最老的人。

public Person getYoungestPerson(Object [] arr){

    int i=0; Person youngest;
    while(person == null){
      if(arr[i] instanceof Person) youngest = arr[i];
      i++;
      }
     for(i=0;i<arr.length;i++){ if (arr[i] instanceof Person) 
            if(arr[i].getDateOfBirth()<youngest.getDateOfBirth()) 
               youngest= arr[i];}
   return youngest;
}

理想情況下,Employee應該是Person的子類,並且您將擁有Person數組。 如果你想要Persons,你必須要小心,因為instanceof也為所有子類返回true,這不是你的情況,因為Employee不會擴展Person,只是未來。

在Employee和Person類中編寫一些get方法。 例如,

在您的Employee類中,創建:

public int getSalary(){
  return salary; // Make salary as a global variable
}

在你的Person類中,做

public int getYear(){
  return year; // same here
}

所以在你的主要代碼中,你可以做到

for (int i = 1; i < array.length; i++){
  Object youngest;
  if (crr[i].getYear() < crr[i+1].getYear())){
    youngest = crr[i];
  }
}

但是,我實際上建議您使用ArrayList而不是array。 並創建兩個數組/ ArrayLists而不是將e和p放在一個數組中。 更易於管理。

不要使用Object類型的數組。 Java擅長打字,所以要充分利用它。 如果Person擴展Employee,或Employee擴展Person,則利用它。 使用頂級類初始化數組:

Person[] people = {new Employee(...), new Employee(...),
  new Person(...), new Person(...)};

要么

Person[] people;
...
people = new People[]{new Employee(...), 
  new Employee(...), new Person(...), new Person(...)};

要么

Person[] people = new People[<some number>];
...
people[0] = new Employee(...);
people[1] = new Person(...);
...

然后我們可以通過確保Person(或Employee)實現Comparable(或Employee),實現compareTo(Person other){...}(或Employee),並調用Arrays.sort(people)來對數組進行排序。 因為我們使它們具有可比性,Java將知道如何對它們進行排序。

Java可以為你做很多事情,但你必須遵守它的規則。 不使用“Object”容器就是其中之一,實現Comparable接口是另一個(第三個是在ArrayList,HashMap等容器上使用泛型,這樣Java就知道你在它們中放了什么,而不是捕獲它們 - 所有“對象”)

如果Person不通過擴展與Employee“相關”,則可以強制兩個類實現相同的接口。 創建該接口類型的數組並將Employee和Person對象放入其中。 然后使用接口方法比較Employee和Person對象。 我認為這里最好的選擇是讓Employee擴展Person,但接口可以提供一個很好的選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM