本文共 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/