There is a designer
public CustomizedComparator(Comparator<T>... comparators) { this.comparators = comparators; } The question is, what do these three points mean in it?
There is a designer
public CustomizedComparator(Comparator<T>... comparators) { this.comparators = comparators; } The question is, what do these three points mean in it?
This is a constructor with a variable number of arguments of type Comparator<T> .
In your class, the field this.comparators probably has the type Comparator<T>[] - that is, an array of comparators.
You can call such a constructor, for example, in the following ways:
CustomizedComparator();
CustomizedComparator(comparator);
CustomizedComparator(intCompataror, longComparator, stringComparator);
and so on.
In fact, it is syntactic sugar for transferring arrays to methods / constructors.
JDK 5 has added new functionality that simplifies the creation of methods that accept a variable number of arguments. This feature is called varargs .
The abbreviation of the term variable-length arguments is variable length arguments.
A method that accepts a variable number of arguments is called a variable arity method, or simply a varargs method.
Thanks for the clarification and answers. I tried it in practice, conveniently.
public class Solution { public static void main(String[] args) { ArrayList<Woman> women = new ArrayList<Woman>(); women.add(new Woman("Катя", "Катина", 18)); women.add(new Woman("Маша", "Машина",21)); women.add(new Woman("Катя", "Сакина",5)); Comparator<Woman> compareByName = new Comparator<Woman>() { public int compare(Woman o1, Woman o2) { return o1.name.compareTo(o2.name); } }; Comparator<Woman> compareByHeight = new Comparator<Woman>() { public int compare(Woman o1, Woman o2) { return o1.age - o2.age; } }; Comparator<Woman> compareBySurname = new Comparator<Woman>() { public int compare(Woman o1, Woman o2) { return o1.surname.compareTo(o2.surname); } }; //Collections.sort(women, compareByHeight); CustomizedComparator<Woman> customizedComparator = new CustomizedComparator<Woman>(compareByName, compareByHeight); Collections.sort(women, customizedComparator); for (Woman w : women) { System.out.println(w.name + " " + w.surname + " " + w.age); } } public static class CustomizedComparator<T> implements Comparator<T> { private Comparator<T>[] comparators; public CustomizedComparator(Comparator<T>... comparators) { this.comparators = comparators; } @Override public int compare(T o1, T o2) { int result = 0; for (int i = 0; i < comparators.length; i++) { result = comparators[i].compare(o1,o2); if (result != 0) { break; } } return result; } } public static class Woman { public String name; public String surname; public int age; public Woman(String name, String surname, int age) { this.age = age; this.name = name; this.surname = surname; } } }
Source: https://ru.stackoverflow.com/questions/677311/
All Articles
Comparator<T>... comparatorssimilar toComparator<T>[] comparatorsis an array designation - MrFylypenko