亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Java JavaBase Sorting of Java Basics TreeSet and Java Custom Types

Sorting of Java Basics TreeSet and Java Custom Types

Mar 05, 2021 am 09:54 AM
java treeset customize

Sorting of Java Basics TreeSet and Java Custom Types

TreeSet and Java custom type sorting

  • Demonstrates that TreeSet can sort String
  • TreeSet Unable to sort custom types
  • How to write comparison rules
  • Self-balancing binary tree structure
  • Implementing the comparator interface
  • Collections tool class

(Free learning recommendation: java basic tutorial)

Demonstrates TreeSet pairing String is sortable

1. The bottom layer of the TreeMap collection is actually a TreeMap
2. The bottom layer of the TreeMap collection is a binary tree
3. The elements placed in the TreeSet collection , which is equivalent to being placed in the key part of the TreeMap collection.
4. The elements in the TreeSet collection are unordered and cannot be repeated, but they can be automatically sorted according to the size of the elements.

is called: a sortable collection
For example: write a program to retrieve data from the database, and display user information on the page in ascending or descending order by birthday.
You can use the TreeSet collection at this time, because the TreeSet collection is put in and taken out in order. of.

//創(chuàng)建一個TreeSet集合
??TreeSet<string>?ts=new?TreeSet();
??//添加Stringts.add("zhangsan");ts.add("lisi");ts.add("wangwu");ts.add("zhangsi");ts.add("wangliu");for(String?s:ts){
??????//按照字典順序排序
??????System.out.print(s+"?");
??}
??TreeSet<integer>?ts2=new?TreeSet();ts2.add(100);ts2.add(200);ts2.add(900);ts2.add(800);??ts2.add(600);ts2.add(10);for(Integer?i:ts2){
??????//按照升序排序
??????System.out.print(i+"?");}</integer></string>

Sorting of Java Basics TreeSet and Java Custom Types

TreeSet cannot sort custom types

Can TreeSet sort custom types?
In the following program, the Person class cannot be sorted because the comparison rules between Person objects are not specified. It is not stated who is older and who is younger.

public?class?TreeSetTest02?{
????public?static?void?main(String[]?args)?{
????????Person?p1=new?Person(50);
????????Person?p2=new?Person(10);
????????Person?p3=new?Person(20);
????????Person?p4=new?Person(60);
????????Person?p5=new?Person(40);
????????Person?p6=new?Person(30);
????????TreeSet<person>?persons=new?TreeSet();
????????persons.add(p1);
????????persons.add(p2);
????????persons.add(p3);
????????persons.add(p4);
????????persons.add(p5);
????????persons.add(p6);
????????for(Person?p:persons){
????????????System.out.println(p);
????????}
????}}class?Person{
????int?age;
????public?Person(int?age){
????????this.age=age;
????}
????@Override
????public?String?toString()?{
????????return?"Person?[age="?+?age?+?"]";
????}}</person>
Exception?in?thread?"main"?java.lang.ClassCastException:?testCollection.Person?cannot?be?cast?to?java.lang.Comparable

The reason for this error is that the
Person class does not implement the java.lang, Comparable interface

//Put it in the TreeSet collection The elements in need to implement the java.lang.Comparable interface
//And implement the compareTo method, equals does not need to be written

??public?class?TreeSetTest04?{
????????public?static?void?main(String[]?args)?{
????????????Customer?p1=new?Customer(50);
????????????Customer?p2=new?Customer(10);
????????????Customer?p3=new?Customer(20);
????????????Customer?p4=new?Customer(60);
????????????Customer?p5=new?Customer(40);
????????????Customer?p6=new?Customer(30);
????????????TreeSet<customer>?customers=new?TreeSet();
????????????customers.add(p1);
????????????customers.add(p2);
????????????customers.add(p3);
????????????customers.add(p4);
????????????customers.add(p5);
????????????customers.add(p6);
????????????for(Customer?p:customers){
????????????????System.out.println(p);
????????????}
????????}
????}
????//放在TreeSet集合中的元素需要實現(xiàn)java.lang.Comparable接口//并且實現(xiàn)compareTo方法,equals可以不寫
????class?Customer?implements?Comparable<customer>{
????????int?age;
????????public?Customer(int?age){
????????????this.age=age;
????????}
????????@Override
????????public?String?toString()?{
????????????return?"Customer?[age="?+?age?+?"]";
????????}
????????//需要在這個方法中編寫比較的邏輯,或者說比較的規(guī)則,按照什么進行比較。
????????//k.compareTo(t.key)
????????//拿著參數(shù)k和集合中的每個k進行比較,返回值可能是>0,age2){//???????return?1;//????}else{//???????return?-1;//????}
????????????return?this.age-c.age;????//>,<p>//You need to write the comparison logic in this method, or compare The rules according to which comparisons are made. <br> //k.compareTo(t.key)<br> //Compare parameter k with each k in the set. The return value may be >0, / /<strong>Comparison rules are ultimately implemented by programmers: for example, in ascending order by age, or in descending order by age</strong></p>
<p><strong>How to write comparison rules</strong></p>
<p>First sort by age Ascending order, if the age is the same, then order by name in ascending order </p>
<pre class="brush:php;toolbar:false">public?class?TreeSetTest05?{
????public?static?void?main(String[]?args)?{
????????TreeSet<vip>?vips=new?TreeSet();
????????vips.add(new?Vip("zhangsi",20));
????????vips.add(new?Vip("zhangsan",20));
????????vips.add(new?Vip("king",18));
????????vips.add(new?Vip("soft",17));
????????for(Vip?vip:vips){
????????????System.out.println(vip);
????????}
????}}class?Vip?implements?Comparable<vip>{
????String?name;
????int?age;
????public?Vip(String?name,int?age){
????????this.name=name;
????????this.age=age;
????}
????@Override
????public?String?toString()?{
????????return?"Vip?[name="?+?name?+?",?age="?+?age?+?"]";
????}
????//compareTo方法的返回值很重要:
????//返回0表示相同,value會覆蓋
????//>0,會繼續(xù)在右子樹上找
????//<p><strong>Self-balancing binary tree structure</strong></p>
<p>1.<strong>Self-balancing binary tree, follow the principle of small left and large right </strong><br> 2. There are three ways to traverse a binary tree <br> Pre-order traversal: left and right roots <br> In-order traversal: left and right roots <br> Post-order traversal: left and right roots <br> Note: front and center What I will talk about later is the location of the root<br> 3.<strong>TreeSet collection and TreeMap collection use in-order traversal, that is, left root and right. They are self-balancing binary trees</strong><br> 100 200 50 60 80 120 140 130 135 180 666</p>
<p><strong>Implement the comparator interface</strong></p>
<p>The elements in the TreeSet collection can be sorted The second way is to use a comparator</p>
<pre class="brush:php;toolbar:false">public?class?TreeSetTest06?{
????public?static?void?main(String[]?args)?{
????????//創(chuàng)建TreeSet集合的時候,需要使用比較器
????????//TreeSet<wugui>?wuGuis=new?TreeSet();???//這樣不行,沒有通過構造方法傳遞一個比較器進去
????????TreeSet<wugui>?wuGuis=new?TreeSet(new?WuguiComparator());
????????wuGuis.add(new?Wugui(1000));
????????wuGuis.add(new?Wugui(800));
????????wuGuis.add(new?Wugui(900));
????????wuGuis.add(new?Wugui(300));
????????wuGuis.add(new?Wugui(60));
????????for(Wugui?wugui:wuGuis){
????????????System.out.println(wugui);
????????}

????}}class?Wugui{
????int?age;

????public?Wugui(int?age)?{
????????super();
????????this.age?=?age;
????}

????@Override
????public?String?toString()?{
????????return?"Wugui?[age="?+?age?+?"]";
????}}//單獨再這里編寫一個比較器//比較器實現(xiàn)java.util.Comparator接口(Comparable是java.lang包下的)class?WuguiComparator?implements?Comparator<wugui>{
????public?int?compare(Wugui?o1,Wugui?o2){
????????//指定比較規(guī)則
????????//按照年齡排序
????????return?o1.age-o2.age;
????}}</wugui></wugui></wugui>

Sorting of Java Basics TreeSet and Java Custom Types
We can use the anonymous inner class method
We can use the anonymous inner class method (this class has no name , direct new interface)

TreeSet<wugui>?wuGuis=new?TreeSet(new?Comparator<wugui>(){public?int?compare(Wugui?o1,Wugui?o2){
????????//指定比較規(guī)則
????????//按照年齡排序
????????return?o1.age-o2.age;
????????}});</wugui></wugui>

Final conclusion, if you want to sort the elements placed in the key part of the TreeSet or TreeMap collection, there are two ways
The first one: put The elements in the collection implement the java.lang.Comparable interface
The second method: pass a comparator object to it when constructing the TreeSet or TreeMap collection.

How to choose between Comparable and Comparator?
When the comparison rules will not change, or when there is only one comparison rule, it is recommended to implement the Comparable interface
If there are multiple comparison rules and multiple comparison rules are needed For frequent switching between comparison rules, it is recommended to use the comparator interface
The design of the comparator interface complies with OCP principles.

Collections tool class

java.util.Collections collection tool class, which facilitates the operation of collections

public?class?CollectionsTest?{
????static?class?Wugui2?implements?Comparable<wugui2>{
????????int?age;

????????public?Wugui2(int?age)?{
????????????super();
????????????this.age?=?age;
????????}

????????@Override
????????public?String?toString()?{
????????????return?"Wugui2?[age="?+?age?+?"]";
????????}

????????@Override
????????public?int?compareTo(Wugui2?o)?{
????????????//?TODO?Auto-generated?method?stub
????????????return?this.age-o.age;
????????}
????}
????public?static?void?main(String[]?args)?{
????????//ArrayList集合不是線程安全的
????????List<string>?list=new?ArrayList<string>();
????????//變成線程安全的
????????Collections.synchronizedList(list);
????????//排序
????????list.add("abc");
????????list.add("abe");
????????list.add("abd");
????????list.add("abf");
????????list.add("abn");
????????list.add("abm");
????????Collections.sort(list);
????????for(String?s:list){
????????????System.out.println(s);
????????}
????????List<wugui2>?wuguis=new?ArrayList();
????????wuguis.add(new?Wugui2(1000));
????????wuguis.add(new?Wugui2(8000));
????????wuguis.add(new?Wugui2(4000));
????????wuguis.add(new?Wugui2(6000));
????????//注意:對list集合中元素排序,需要保證list集合中元素實現(xiàn)了Comparable接口
????????Collections.sort(wuguis);
????????for(Wugui2?wugui:wuguis){
????????????System.out.println(wugui);
????????}
????????//對set集合怎么排序呢
????????Set<string>?set=new?HashSet();
????????set.add("king");
????????set.add("kingsoft");
????????set.add("king2");
????????set.add("king1");
????????//將set集合轉(zhuǎn)換成list集合
????????List<string>?myList=new?ArrayList(set);
????????Collections.sort(myList);
????????for(String?s:myList){
????????????System.out.println(s);
????????}
????????//這種方式也可以排序
????????//Collections.sort(list集合,比較器對象)
????}}</string></string></wugui2></string></string></wugui2>

Sorting of Java Basics TreeSet and Java Custom Types

Related learning recommendations: java basics

The above is the detailed content of Sorting of Java Basics TreeSet and Java Custom Types. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

python itertools combinations example python itertools combinations example Jul 31, 2025 am 09:53 AM

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

Troubleshooting Common Java `OutOfMemoryError` Scenarios Troubleshooting Common Java `OutOfMemoryError` Scenarios Jul 31, 2025 am 09:07 AM

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

python pytest fixture example python pytest fixture example Jul 31, 2025 am 09:35 AM

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

See all articles