Hello. It's Kecho. ** Do you use TreeSet? ** ** I saw it for the first time today. Have you ever used a similar HashSet or TreeMap?
It is a class that does not allow duplication and sorts and retains when adding. It's a class that seems to be useful in competitive programming.
class Product {
private int id;
private String name;
public Product() {
}
public Product(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
}
I created the id and name fields, the constructor, and the accessor.
Set<Product> tree = new TreeSet<>();
tree.add(new Product(1, "kechong"));
tree.add(new Product(2, "me"));
tree.add(new Product(3, "you"));
for (Product product : tree) {
System.out.print("id:" + product.getId() + ", ");
System.out.print("name:" + product.getName());
System.out.println();
}
Yes, I'll try it.
Exception in thread "main" java.lang.ClassCastException: Product cannot be cast to java.base/java.lang.Comparable
at java.base/java.util.TreeMap.compare(TreeMap.java:1291)
at java.base/java.util.TreeMap.put(TreeMap.java:536)
at java.base/java.util.TreeSet.add(TreeSet.java:255)
at Main.main(Main.java:26)
You got an error.
You're throwing a ClassCastException. I'm angry that the Product can't be cast to Comparable. The place of occurrence is when you try to add to the TreeSet.
I don't have to cast it ... I think, but this is necessary for TreeSet.
TreeSet has the concept of order. When adding to a TreeSet, you need to decide the order to determine where to hold it. When I created the Product class myself, an error occurred because I didn't specify "how to compare Product objects".
Specifically, it implements the Comparable interface.
class Product implements Comparable<Product> {
private int id;
private String name;
public Product() {
}
public Product(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
@Override
public int compareTo(Product o) {
return this.id - o.id;
}
}
Yes, I implemented and overridden the compareTo method.
id:1, name:kechong
id:2, name:me
id:3, name:you
Yes, it looks good!
This time, I implemented the Comparable interface in the Product class. However, when instantiating TreeSet, the same output can be obtained by specifying the following in the argument of the constructor.
Set<Product> tree = new TreeSet<>(Comparator.comparing(Product::getId));
This makes it possible to determine the order by giving a comparison method to the TreeSet side.
If you want to add your own object to TreeSet, you need to do one of the following: -Implement a Comparable interface with your own object -Specify the comparison method in the constructor argument of TreeSet
Recommended Posts