gpt4 book ai didi

java - Java中元组的计数排序

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:36:45 26 4
gpt4 key购买 nike

我正在构建一个具有字符串到整数映射的类。因此,如果我有 3 个苹果,我会将苹果映射到 3 个。

我需要编写一个类,通过递减数字对对象的名称进行排序。

如果我有

(苹果,3 个)(橙子,2 个)(香蕉,5 个)

我会得到(香蕉,5 个),(苹果,3 个),(橙子 2 个)

我想知道是否已经有一个类(class)可以让我的生活更轻松,或者我将如何实现它。

谢谢。

最佳答案

您应该能够将对象 (apples, 3) (oranges, 2) (bananas, 5) 放入列表中,然后调用 Collections.sort(yourlist)。然后,您需要确保您声明的对象实现了 Comparable 接口(interface)。

更多信息请访问 http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html

假设您声明反对

public class FruitAndCount implements Comparable<FruitAndCount> {
private final String name;
private final Integer count;

public FruitAndCount(String name, int count) {
this.name = name;
this.count = count;
}

public String name() { return name; }
public int count() { return count; }

public int compareTo(FruitAndCount o) {
return this.count.compareTo(o.count);
}
}

然后您应该能够进行以下调用,这将对您的列表进行排序:

FruitAndCount fruitArray[] = {
new FruitAndCount("Apples", 3),
new FruitAndCount("Oranges", 2),
new FruitAndCount("Bananas", 5)
};

List<FruitAndCount> fruit = Arrays.asList(fruitArray);
Collections.sort(fruit);

然后您应该有一个排序的水果列表。

关于java - Java中元组的计数排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2125550/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com