博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
list set array map 排序问题
阅读量:6955 次
发布时间:2019-06-27

本文共 2782 字,大约阅读时间需要 9 分钟。

 

 

While analyzing source code of a large number of open source Java projects, I found Java developers frequently sort in two ways. One is using the sort() method of Collections or Arrays, and the other is using sorted data structures, such as TreeMap and TreeSet.

 

1. Using sort() Method

If it is a collection, use Collections.sort() method.

// Collections.sortList
list = new ArrayList
();Collections.sort(list, new Comparator
() {
public int compare(ObjectName o1, ObjectName o2) {
return o1.toString().compareTo(o2.toString()); }});

If it is an array, use Arrays.sort() method.

// Arrays.sortObjectName[] arr = new ObjectName[10];Arrays.sort(arr, new Comparator
() {
public int compare(ObjectName o1, ObjectName o2) {
return o1.toString().compareTo(o2.toString()); }});

This is very convenient if a collection or an array is already set up.

2. Using Sorted Data Structures

If it is a list or set, use TreeSet to sort.

// TreeSetSet
sortedSet = new TreeSet
(new Comparator
() {
public int compare(ObjectName o1, ObjectName o2) {
return o1.toString().compareTo(o2.toString()); }});sortedSet.addAll(unsortedSet);

If it is a map, use TreeMap to sort. TreeMap is sorted by key.

// TreeMap - using String.CASE_INSENSITIVE_ORDER which is a Comparator that orders Strings by compareToIgnoreCaseMap
sortedMap = new TreeMap
(String.CASE_INSENSITIVE_ORDER);sortedMap.putAll(unsortedMap);
//TreeMap - In general, defined comparatorMap
sortedMap = new TreeMap
(new Comparator
() {
public int compare(ObjectName o1, ObjectName o2) {
return o1.toString().compareTo(o2.toString()); }});sortedMap.putAll(unsortedMap);

This approach is very useful, if you would do a lot of search operations for the collection. The sorted data structure will give time complexity of O(logn), which is lower than O(n).

3. Bad Practices

There are still bad practices, such as using self-defined sorting algorithm. Take the code below for example, not only the algorithm is not efficient, but also it is not readable. This happens a lot in different forms of variations.

double t;for (int i = 0; i < 2; i++)	for (int j = i + 1; j < 3; j++)		if (r[j] < r[i]) {
t = r[i]; r[i] = r[j]; r[j] = t; }

转载地址:http://zctil.baihongyu.com/

你可能感兴趣的文章
180321
查看>>
Spark2.1.0之源码分析——事件总线
查看>>
运维高考题
查看>>
PreviewRenderUtility的Example
查看>>
纯JS操作获取桌面路径方法
查看>>
HTTP VISUAL HTTP请求可视化工具、HTTP快照工具(公测)
查看>>
Htmlparser专题
查看>>
scrapy-splash抓取动态数据例子七
查看>>
大数据开发实战:数据平台大图和离线数据平台整体架构
查看>>
《CLR via C#》笔记——异常和状态管理
查看>>
将matlab的figure保存为pdf,避免图片太大缺失
查看>>
Spring MVC 3 深入总结
查看>>
原创4:dell sc1425老服务器安装vmware虚拟机esxi 5.0-更新Dell SCSI Hard Drive Firmware
查看>>
JAVA多线程学习Runnable接口
查看>>
AE Geoprocessor 实现 AnalysisTool Union功能
查看>>
深入理解JVM
查看>>
微观ORACLE(一):PMON Release Lock
查看>>
NC57银行档案和客商银行账号为建行04 UPDATE
查看>>
(转)Objective-C的单例模式(singleton)
查看>>
细说 ASP.NET控制HTTP缓存(转)
查看>>