java arrays sort comparator
时间: 2023-08-30 12:08:56 浏览: 138
Java provides the Arrays class, which has a sort method that allows you to sort arrays. To customize the sort order, you can use a Comparator.
A Comparator is an interface that defines a comparison function. You can create a Comparator implementation and pass it as a parameter to the Arrays.sort() method. The Comparator implementation should override the compare() method to define the sorting logic.
Here's an example of sorting an array of objects using a Comparator:
```java
import java.util.Arrays;
import java.util.Comparator;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class Main {
public static void main(String[] args) {
Person[] people = {
new Person("Alice", 25),
new Person("Bob", 20),
new Person("Charlie", 30)
};
// Sort by age using a custom comparator
Arrays.sort(people, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return Integer.compare(p1.getAge(), p2.getAge());
}
});
// Print sorted array
for (Person person : people) {
System.out.println(person.getName() + " - " + person.getAge());
}
}
}
```
In this example, we have a Person class with name and age attributes. We create an array of Person objects and sort them based on the age using a custom Comparator implementation. The compare() method compares the ages of two Person objects and returns the result of the comparison.
After sorting, the array will be printed in ascending order based on age.
阅读全文