-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathComparableDemo.java
More file actions
67 lines (55 loc) · 1.6 KB
/
ComparableDemo.java
File metadata and controls
67 lines (55 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package learnCollections;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/*
Comparator is used when you have to do custom sorting
Comparable is used to define natural ordering of objects
*/
public class ComparableDemo {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
list.add(new Student("Charlie", 3.5));
list.add(new Student("Bob", 3.7));
list.add(new Student("Alice", 3.5));
list.add(new Student("Akshit", 3.9));
list.sort(null);
System.out.println(list);
}
}
class Student implements Comparable<Student> {
private String name;
private double gpa;
public Student(String name, double gpa) {
this.name = name;
this.gpa = gpa;
}
public String getName() {
return name;
}
public double getGpa() {
return gpa;
}
@Override
public boolean equals(Object obj) {
if(this == obj) return true;
if(obj == null || getClass() != obj.getClass()) return false;
Student other = (Student) obj;
return Double.compare(gpa, other.getGpa()) == 0 && Objects.equals(name, other.getName());
}
@Override
public int hashCode() {
return Objects.hash(name, gpa);
}
@Override
public String toString() {
return "Student{name='" + name + "', gpa=" + gpa + "}";
}
@Override
public int compareTo(Student other) {
if(getGpa() == other.getGpa()) {
return name.compareTo(other.getName());
}
return Double.compare(other.getGpa(), gpa);
}
}