Reputation: 99
Here is my files
User.java
public class User implements Comparable<User> {
private String name;
private int age;
public User(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
/**
* Sorting by name
*/
@Override
public int compareTo(User user) {
return this.name.compareTo(user.name);
}
}
Test.java
public class Test {
public static void main(String[] args) {
User u1=new User("Shanaya", 22);
User u2=new User("Jhon", 27);
User u3=new User("Arya", 20);
Set<User> set=new HashSet<>();
set.add(u1);
set.add(u2);
set.add(u3);
System.out.println(set); //by name sorting not working here
}
Overriden compareTo() is here to compare objects "by names" only Still output of program is "by age" comparison
output: [User [name=Arya, age=20], User [name=Shanaya, age=22], User [name=Jhon, age=27]]
Upvotes: 0
Views: 403
Reputation: 522762
The problem here is that a HashSet
is not an ordered set in Java, and it won't make use of your implementation of the Comparable
interface. Try using an ordered set like TreeSet
instead:
User u1 = new User("Shanaya", 22);
User u2 = new User("Jhon", 27);
User u3 = new User("Arya", 20);
Set<User> set = new TreeSet<>();
set.add(u1);
set.add(u2);
set.add(u3);
for (User user : set) {
System.out.println(user);
}
Upvotes: 3