-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.java
More file actions
63 lines (46 loc) · 1.23 KB
/
App.java
File metadata and controls
63 lines (46 loc) · 1.23 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
package section12;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
class Names implements Comparable<Names> {
private String name;
Names(String name) {
this.name = name;
}
@Override
public int compareTo(Names obj) {
if (name.length() == obj.name.length())
return 0;
else if (name.length() < obj.name.length()) {
return -1;
} else
return 1;
}
@Override
public String toString() {
return this.name;
}
}
public class App {
void printList(List<Names> list) {
ListIterator<Names> iterator = list.listIterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
System.out.println("------------------------------");
}
public static void main(String[] args) {
List<Names> names = new LinkedList<>();
names.add(new Names("Nirmala"));
names.add(new Names("Dinesh"));
names.add(new Names("Kamalesh"));
names.add(new Names("Anand"));
App app = new App();
app.printList(names);
// now sorting the list, as we override compareTo method, it will sort on the
// basis of our logic there as per the length of the string
Collections.sort(names); // this will invoke compareTo()
app.printList(names);
}
}