Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

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

2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report