Skip to content

Commit 04b7779

Browse files
author
Alan
committedJun 25, 2020
compareTo
1 parent cf3ffb9 commit 04b7779

File tree

3 files changed

+100
-0
lines changed

3 files changed

+100
-0
lines changed
 

‎CompareTo/Main.java

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import static java.lang.System.*;
2+
import java.util.*;
3+
public class Main
4+
{
5+
static void log(Object o){out.print(o);}
6+
static void logLn(Object o){out.println(o);}
7+
8+
public static void main(String [] args)
9+
{
10+
TreeSet<User> users = new TreeSet<>();
11+
users.add(new User("Kevin", "Nguyen"));
12+
users.add(new User("Lyndon", "Nguyen"));
13+
users.add(new User("Vince", "Li"));
14+
users.add(new User("Alan", "Ngo"));
Has a conversation. Original line has a conversation.
15+
users.add(new User("Varshika", "Pichela"));
16+
users.add(new User("Lucinda", "Nguyen"));
17+
users.add(new User("Carlos", "Ovalle"));
18+
users.add(new User("Smruti", "Shah"));
19+
20+
logLn(users);
21+
// Should print
22+
// [Alan Ngo, Carlos Ovalle, Kevin Nguyen, Lucinda Nguyen, Lyndon Nguyen, Varshika Pichela, Vince Li, Smruti Shah]
23+
}
24+
}

‎CompareTo/README.md

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Comparing Objects
2+
3+
#### class needs to implement java.lang.Comparable
Has a conversation. Original line has a conversation.
4+
5+
```java
6+
public class Student implements Comparable<Student>
7+
{
8+
...
9+
}
10+
```
11+
12+
useful for
13+
- sorting
14+
- TreeSet
15+
- TreeMap
16+
17+
Need to implement
18+
19+
```java
20+
@Override
21+
public int compareTo(Student arg0)
22+
{
23+
if (arg0 == this)
24+
return 0;
25+
26+
// logic goes here
27+
...
28+
}
29+
```

‎CompareTo/User.java

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import static java.util.Objects.*;
2+
public class User implements Comparable<User>
3+
{
4+
private final String firstName;
5+
private final String lastName;
6+
7+
public User(String fN, String lN)
8+
{
9+
firstName = fN;
10+
lastName = lN;
11+
}
12+
13+
14+
// overriden from java.lang.Object
15+
@Override
16+
public String toString(){return firstName+" "+ lastName;}
17+
18+
@Override
19+
public boolean equals(Object o)
20+
{
21+
if (!(o instanceof User))
22+
return false;
23+
24+
if (o == this)
25+
return true;
26+
27+
User u = (User) o;
28+
return this.firstName.equals(u.firstName)
29+
&& this.lastName.equals(u.lastName);
30+
}
31+
32+
@Override
33+
public int hashCode(){return hash(firstName, lastName);}
34+
35+
//overriden from java.lang.Comparable
36+
@Override
37+
public int compareTo(User arg0)
38+
{
39+
if (arg0 == this)
40+
return 0;
41+
42+
// we want to sort by first AND last name
43+
return this.firstName.compareTo(arg0.firstName)+
44+
this.lastName.compareTo(arg0.lastName);
45+
}
46+
47+
}

0 commit comments

Comments
 (0)
Please sign in to comment.