[introduction to Java] day31 detailed explanation of Java container class (XIII) detailed explanation of TreeSet

After the introduction of treemap in the previous article, let's take a look at the more water TreeSet.

This paper will be expanded from the following perspectives:

1. Introduction to TreeSet and use of chestnuts

2. TreeSet source code analysis

This article takes about 10 minutes to eat. Please enjoy yourself.

1、 Introduction to TreeSet

TreeSet is another lazy general in the set family. Like the other two, TreeSet is closely related to the corresponding map

Let's first review the other two set classes. HashSet has the feature of fast element insertion and search with the help of HashMap, linkedhashset has the feature of fast insertion and search and maintaining the insertion order of elements with the help of LinkedHashMap, and TreeSet has the feature of maintaining the order of internal elements with the help of treemap. Of course, All set collection classes have the feature of element de duplication. Of course, the difference is that the order in TreeSet means that the inserted elements can be sorted according to the order of the internal comparator or the external comparator, that is, the order will be adjusted after each insertion to maintain the overall order of the internal elements, while the linkedhashset can only maintain the insertion order of the elements.

  Talk is cheap,show me your code. Well, let's look at the code:

The output is as follows:

You can see that TreeSet automatically sorts the inserted elements. So can we put in our custom class elements? Of course, it can. Otherwise, what's the use of it

The output is as follows:

Welcome to the large rollover site...

Don't panic, don't panic, it's not a problem. Like treemap, TreeSet requires elements to implement the comparable interface or pass in an external comparator. Why can string not be used? Look at the implementation of string. Others have implemented the comparable interface.

So there are two ways to solve this problem. One is to let the goods class implement the comparable interface, and the other is to pass in an external comparator. Let's look at the first one first:

In order to see the effect, the order of several commodities is adjusted, and the output is as follows:

Here we arrange the prices in ascending order, and then use the external comparator to arrange the prices in reverse order:

There are also many gestures when passing in the external comparator. Here, the anonymous internal class is selected for passing in, because it only needs to be used once. The lamada expression has not been introduced yet. I won't talk about it first. Just enjoy it and appreciate its power first.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>