Меня заинтриговал тот факт, что сегодня я заметил
что для сравнения в Java
Integer предусмотрен метод сравнения
Integer.compare(student1.age, student2.age);
String предоставляет метод CompareTo
Student1.firstName.compareTo(student2.firstName);
Просто хочу понять, почему:/
Пожалуйста, обратитесь к примеру класса здесь:
String firstName;
String lastName;
int age;
long studentId;
Student(){}
Student(String firstName, String lastName, int age, long studentId){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.studentId = studentId;
}
}
Реализации Кампаратора –
public class StudentFirstNameComparator implements Comparator {
@Override
public int compare(Student student1, Student student2) {
return student1.firstName.compareTo(student2.firstName);
}
}
public class StudentAgeComparator implements Comparator {
@Override
public int compare(Student student1, Student student2) {
return Integer.compare(student1.age, student2.age);
// either of the lines can be used.
// if(student1.age == student2.age)
// return 0;
// else if (student1.age>student2.age) {
// return 1;
// }else {
// return -1;
// }
}
}
Подробнее здесь: https://stackoverflow.com/questions/732 ... od-in-java
Почему Integer имеет метод «сравнить», а строка имеет метод «compareTo» в Java ⇐ JAVA
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Почему .max (Integer :: max) и .min (Integer :: min) компилируют на потоке Java 8?
Anonymous » » в форуме JAVA - 0 Ответы
- 123 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Почему .max (Integer :: max) и .min (Integer :: min) компилируют на потоке Java 8?
Anonymous » » в форуме JAVA - 0 Ответы
- 106 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Почему использование Integer.parseInt для строки «Integer.MAX_VALUE» не работает?
Anonymous » » в форуме JAVA - 0 Ответы
- 38 Просмотры
-
Последнее сообщение Anonymous
-