简体   繁体   English

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

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

I am creating an array of type Object. 我正在创建一个Object类型的数组。 I have two different classes, Employee and Person which have simple attributes like name, salary (Employee) first name, date of birth (Person). 我有两个不同的类,Employee和Person,它们具有简单的属性,如姓名,薪水(员工)名字,出生日期(人)。 I need to add some Employee and Person objects into my array and compare certain things within the array. 我需要在我的数组中添加一些Employee和Person对象,并比较数组中的某些内容。 Ex, retrieving the youngest Person from the array. 例如,从数组中检索最年轻的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("--------------------");
}   
}

How would I compare certain things on the array. 我如何比较阵列上的某些东西。 Like printing the youngest person,, which means I have to look through the array and see if its a Person object then getDateOfBirth on those objects and print the oldest person. 就像打印最年轻的人一样,这意味着我必须查看数组并查看它是否为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;
}

Ideally, Employee should be a child class from Person, and you would have a Person array. 理想情况下,Employee应该是Person的子类,并且您将拥有Person数组。 You have to be careful if you want only Persons, because instanceof also returns true for all child classes, this is not your case, because Employee does not extends Person, just a heads up to the future. 如果你想要Persons,你必须要小心,因为instanceof也为所有子类返回true,这不是你的情况,因为Employee不会扩展Person,只是未来。

Write some get methods in your Employee and Person classes. 在Employee和Person类中编写一些get方法。 For example, 例如,

in your Employee class, create: 在您的Employee类中,创建:

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

In your Person class, do 在你的Person类中,做

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

So in you main code, you can do 所以在你的主要代码中,你可以做到

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

However, I actually would like to recommend you to use ArrayList instead of array. 但是,我实际上建议您使用ArrayList而不是array。 And Creat two arrays/ArrayLists instead of putting e and p in one array. 并创建两个数组/ ArrayLists而不是将e和p放在一个数组中。 Easier to manage. 更易于管理。

Don't use arrays of type Object. 不要使用Object类型的数组。 Java excels at strong typing, so take advantage of that. Java擅长打字,所以要充分利用它。 If Person extends Employee, or Employee extends Person, exploit that. 如果Person扩展Employee,或Employee扩展Person,则利用它。 Initialise your array with the top class: 使用顶级类初始化数组:

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

or 要么

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

or 要么

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

And then we can sort the array by making sure Person (or Employee) implements Comparable (or Employee), implementing compareTo(Person other) {...} (or Employee), and calling Arrays.sort(people). 然后我们可以通过确保Person(或Employee)实现Comparable(或Employee),实现compareTo(Person other){...}(或Employee),并调用Arrays.sort(people)来对数组进行排序。 Because we made them comparable, Java will know how to sort them. 因为我们使它们具有可比性,Java将知道如何对它们进行排序。

There's a lot of things Java can do for you, but you'll have to play by its rules. Java可以为你做很多事情,但你必须遵守它的规则。 Not using "Object" containers is one of them, implementing the Comparable interface is another (a third one is to use generics on containers like ArrayList, HashMap, etc, so that Java knows what you're putting in them, rather than the catch-all "Object") 不使用“Object”容器就是其中之一,实现Comparable接口是另一个(第三个是在ArrayList,HashMap等容器上使用泛型,这样Java就知道你在它们中放了什么,而不是捕获它们 - 所有“对象”)

If Person isn't "related" to Employee through extension you could force both classes to implement the same interface. 如果Person不通过扩展与Employee“相关”,则可以强制两个类实现相同的接口。 Create and array of that interface type and put Employee and Person objects into it. 创建该接口类型的数组并将Employee和Person对象放入其中。 Then use the interface methods to compare Employee and Person objects. 然后使用接口方法比较Employee和Person对象。 I think the best option here is to have Employee extend Person, but interfaces can provide a nice alternative. 我认为这里最好的选择是让Employee扩展Person,但接口可以提供一个很好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM