Get the App
SLTechnology News&Howtos  ›  Development  › 

What are the methods for Collections.sort to sort List in Java

Shulou Source: shulou.com Published: 2022-06-02 08:29:31 09月15日 Update

This article introduces the relevant knowledge of "what is the method of Collections.sort sorting List in Java". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Simple use of Collections.sort

When it comes to the sorting of List, the first reaction is of course to use Collections.sort, which is convenient and simple. Let's implement ~ ~

Private void sortStrings () {List list = new ArrayList (); list.add ("ccc"); list.add ("aaa"); list.add ("bbb"); / / sort Collections.sort (list); / / output Log.d (TAG, "- sort strings -"); for (String item: list) {Log.d (TAG, item.toString ());}}

= 02-03 10 32 25.821: D/wxx (4732):-sort strings-

02-03 10 32 virtual 25.821: D/wxx (4732): aaa

02-03 10 32 virtual 25.821: D/wxx (4732): bbb

02-03 10 32 virtual 25.821: D/wxx (4732): ccc

It can be seen that the sorting of List is realized, which is very simple.

II. Asking questions

However, in our project, the element type of the list List is often customized. Here is a custom entity class Person:

Public class Person {private String name; private int age; public Person (String name, int age) {this.name = name; this.age = age;}}

Then, if you want to sort the list List of Person, the first thing that comes to mind is also sorting through Collections.sort:

Private void sortPerson () {Person p1 = new Person ("ccc", 20); Person p2 = new Person ("aaa", 18); Person p3 = new Person ("bbb", 16); List list = new ArrayList (); list.add (p1); list.add (p2); list.add (p3); / / sort Collections.sort (list);}

It was found that the code directly reported an error:

Bound mismatch: The generic method sort (List) of type Collections is not applicable for the arguments (List). The inferred type Person is not a valid substitute for the bounded

Parameter

Tags: Sort name entity comparator rule method output result age code character string object that is interface type that is content place suggestion Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Redmi OPPO Reno Shulou Technology vpn