Home > Software design >  Printing specific element in array of objects in java
Printing specific element in array of objects in java

Time:06-07

I am working on a small program where I created employee array of objects with name, salary and date of joining. Is there any method can i get name by order or salary in between like that.

CodePudding user response:

You can use Arrays.sort with a Comparator

https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#sort(T[], java.util.Comparator)

public class Employee {
  String name;
  double salary;
  Date date;
}

public MyComparable implements Comparable<Employee> {
  public int compare (Employee a, Employee b) {
    return b.salary - a.salary;
  }
}


Employee[] employees = ...;
Arrays.sort(employees, new MyComparable);

CodePudding user response:

If you want to sort i recommend you to implement Comparable and override the compare methode so it will be local in your Employee class and you don't have to think where to declaried your compartor. Also i highly recommend you to use a List and not an Array but here is the answer for both:

public class Employee implements Comparable<Employee> {
  String name;
  double salary;
  Date date;

...

@Override
public int compare (Employee other) {
    return this.salary - other.salary;
  }
}

Employee[] employees = ...;
//uses by default the comparator of the class 
Arrays.sort(employees);


List<Employee> employees = ...;
//uses by default the comparator of the class
Collection.sort(employees);
  •  Tags:  
  • java
  • Related