博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
将Java的Arrays.sort()用于任何对象列表
阅读量:2520 次
发布时间:2019-05-11

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

Sorting can be tricky, especially when your list is not of a primitive Java numeric type (Byte, Integer, Short, Long, Double, Float). Now, all situations will vary so this method might not be the best case. However, I’ve found it incredibly useful for simple coding challenges and university lab assignments.

排序可能很棘手,特别是当您的列表不是原始Java数字类型(字节,整数,短,长,双精度,浮点型)时。 现在,所有情况都会有所不同,因此此方法可能不是最佳情况。 但是,我发现它对于简单的编码挑战和大学实验室任务非常有用。

To start, pick your list. For this example I’ll be using a list of Edges from a simple Graph data structure:

首先,选择您的列表。 对于此示例,我将使用来自简单Graph数据结构的Edges列表:

// Very simple Edge classpublic class Edge {    public Vertex src;    public Vertex dst;    public double cost;        // creates an edge between two vertices    Edge(Vertex s, Vertex d, double c) {        src = s;        dst = d;        cost = c;    }}
// List of edgesEdge[] edges = graph.getEdges();

Next, define the implementation of the java.util.Comparator interface:

接下来,定义java.util.Comparator接口的实现:

class SortByCost implements Comparator
{ public int compare(Edge a, Edge b) { if ( a.cost < b.cost ) return -1; else if ( a.cost == b.cost ) return 0; else return 1; }}

In this example, we will be sorting the edges by their cost, or distance from the src (source) vertex to the dst (destination) vertex.

在此示例中,我们将根据edges的成本或src (源)顶点到dst (目标)顶点的距离对edges进行排序。

Finally use the standard java.util.Arrays.sort() method:

最后使用标准的java.util.Arrays.sort()方法:

Arrays.sort(edges, new SortByCost())

And just like that, the list of Edges is now sorted in ascending (least to greatest) order.

就像这样, Edges列表现在按升序(从最小到最大)排序。

If you have any questions feel free to reach out on

如果您有任何疑问,请随时与

You can also find me on or my personal

您也可以在或我的个人上找到我

~ Happy Coding

〜快乐编码

— Ethan Arrowood

—伊桑·艾罗德(Ethan Arrowood)

翻译自:

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

你可能感兴趣的文章
unity3d 射弹基础案例代码分析
查看>>
thinksns 分页数据
查看>>
os模块
查看>>
最短路径(SP)问题相关算法与模板
查看>>
js算法之最常用的排序
查看>>
Python——交互式图形编程
查看>>
经典排序——希尔排序
查看>>
团队编程项目作业2-团队编程项目代码设计规范
查看>>
英特尔公司将停止910GL、915GL和915PL芯片组的生产
查看>>
Maven配置
查看>>
HttpServletRequest /HttpServletResponse
查看>>
SAM4E单片机之旅——24、使用DSP库求向量数量积
查看>>
从远程库克隆库
查看>>
codeforces Unusual Product
查看>>
hdu4348 - To the moon 可持久化线段树 区间修改 离线处理
查看>>
正则表达式的搜索和替换
查看>>
个人项目:WC
查看>>
地鼠的困境SSL1333 最大匹配
查看>>
flume+elasticsearch+kibana遇到的坑
查看>>
【MM系列】在SAP里查看数据的方法
查看>>