[JAVA] How to use TreeSet

Introduction

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?

What is TreeSet?

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.

Try using

First, create an object to add to the TreeSet

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.

Then add an instance

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.

What kind of 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.

Why you are trying to cast

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".

Add the concept of comparison

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.

If you run it again ...

id:1, name:kechong
id:2, name:me
id:3, name:you

Yes, it looks good!

By the way

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.

Summary

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

How to use TreeSet
How to use rbenv
How to use letter_opener_web
How to use with_option
How to use java.util.logging
How to use map
How to use Twitter4J
How to use active_hash! !!
How to use hidden_field_tag
[How to use label]
How to use identity
How to use hashes
How to use JUnit 5
How to use Dozer.mapper
How to use Gradle
How to use org.immutables
How to use java.util.stream.Collector
How to use VisualVM
How to use Map
[Java] How to use Map
How to use Chain API
[Java] How to use Map
How to use Priority Queuing
[Rails] How to use enum
How to use java Optional
How to use JUnit (beginner)
How to use Ruby return
[Rails] How to use enum
How to use @Builder (Lombok)
[Swift] How to use UserDefaults
How to use java class
How to use Swift UIScrollView
How to use Big Decimal
[Java] How to use Optional ②
[Java] How to use removeAll ()
How to use String [] args
[Java] How to use string.format
How to use rails join
How to use Java Map
Ruby: How to use cookies
How to use dependent :: destroy
How to use Eclipse Debug_Shell
How to use Apache POI
[Rails] How to use validation
How to use Java variables
[Rails] How to use authenticate_user!
[Rails] How to use "kaminari"
How to use GC Viewer
[Java] How to use Optional ①
How to use Lombok now
[Creating] How to use JUnit
[Rails] How to use Scope
How to use the link_to method
[Rails] How to use gem "devise"
How to use Lombok in Spring
How to use StringBurrer and Arrays.toString.
How to use arrays (personal memorandum)
How to use Java HttpClient (Get)
How to use the include? method
How to use the form_with method
[Rails] How to use flash messages