Object类型的数组,并比较数组中的对象

时间:2013-02-07 00:00:35

标签: java arrays object

我正在创建一个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并打印最老的人。

4 个答案:

答案 0 :(得分:1)

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数组。如果你想要人,你必须要小心,因为instanceof也为所有子类返回true,这不是你的情况,因为Employee没有扩展Person,只是一个未来。

答案 1 :(得分:1)

在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放在一个数组中。更易于管理。

答案 2 :(得分:0)

不要使用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将know如何对它们进行排序。

Java可以为您做很多事情,但您必须按照规则行事。不使用“Object”容器就是其中之一,实现Comparable接口是另一个(第三个是在ArrayList,HashMap等容器上使用泛型,这样Java就知道你在它们中放了什么,而不是捕获它们-all“对象”)

答案 3 :(得分:0)

如果Person不通过扩展与Employee“相关”,则可以强制两个类实现相同的接口。创建该接口类型的数组并将Employee和Person对象放入其中。然后使用接口方法比较Employee和Person对象。   我认为这里最好的选择是让Employee扩展Person,但接口可以提供一个很好的选择。

相关问题