-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
86 lines (64 loc) · 2.36 KB
/
Main.java
File metadata and controls
86 lines (64 loc) · 2.36 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.dj;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Random;
public class Main {
public static void main(String[] args) {
Integer five = 5;
Integer[] others = {0, 5, 10, -50, 50};
for (Integer i : others){
int val = five.compareTo(i);
System.out.printf("%d %s %d: compareTo=%d %n ", five,(val == 0 ? "==": (val < 0) ? "<":">"),i,val);
}
String banana = "banana";
String[] fruit = {"apple","banana","pear","BANANA"};
for (String s : fruit){
int val = banana.compareTo(s);
System.out.printf("%s %s %s: compareTo=%d%n", banana,(val ==0 ? "==" : (val < 0) ? "<" : ">"),s,val);
}
Arrays.sort(fruit);
System.out.println(Arrays.toString(fruit));
System.out.println("A:" + (int)'A' + " " + "a:" + (int)'a');
System.out.println("B:" + (int)'B' + " " + "b:" + (int)'b');
System.out.println("P:" + (int)'P' + " " + "p:" + (int)'p');
Student tim = new Student("Tim");
Student[] students = {new Student("Zach"),new Student("Tim"), new Student("Ann")};
Arrays.sort(students);
System.out.println(Arrays.toString(students));
System.out.println("result = " + tim.compareTo(new Student("TIM")));
Comparator<Student> gpaSorter =new StudentGPAComparator();
Arrays.sort(students,gpaSorter.reversed());
System.out.println(Arrays.toString(students));
}
}
class StudentGPAComparator implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2){
return (o1.gpa + o1.name).compareTo(o2.gpa + o2.name);
}
}
class Student implements Comparable<Student>{
private static int LAST_ID =1000;
private static Random random = new Random();
String name;
private int id;
protected double gpa;
public Student(String name) {
this.name = name;
id = LAST_ID++;
gpa = random.nextDouble(1.0,4.0);
}
@Override
public String toString() {
return "%d - %s (%.2f)".formatted(id,name,gpa);
}
@Override
public int compareTo(Student o) {
return Integer.valueOf(id).compareTo(Integer.valueOf(o.id));
}
// @Override
// public int compareTo(Object o) {
// Student other = (Student) o;
// return name.compareTo(other.name);
// }
}