gpt4 book ai didi

java - 按对象的属性或方法*但按不同的排序顺序 = ABC、BCA、CAB 等对数组列表进行排序

转载 作者:行者123 更新时间:2023-11-30 02:21:47 24 4
gpt4 key购买 nike

我有一个列表,其中包含具有变量的项目,该变量可能包含3个不同值中的1个。我希望能够根据给定的值对列表进行排序,以便列表最终为: [b,b,b, c,c,c, a,a,a] 或我选择的任何图案。(其中 b、c 或 a 是 MyItem 的 itemType 的表示,请参阅下面的代码。)

排序后的列表将最终显示为 [MyItem、MyItem、MyItem ...等等],只是排序后,itemType = b 的 MyItem 首先出现,然后类型 c 出现第二位,然后类型 a 出现第三位。

也许描述我想要的更好的方式是分组或按组排序?

public class MyItem {
// possible values for item type
public static final int ITEM_TYPE_A = 0x0;
public static final int ITEM_TYPE_B = 0x1;
public static final int ITEM_TYPE_C = 0x2;

protected int itemType;
}

public class ArrayThing {
ArrayList<MyItem> list;

public void sortBy(int sortOrder) {
/* sort items in list by sortOrder takes a 3 digit int
representing the order examples: 123 = ABC, 321 = CBA
*/
switch(sortOrder) {
case(123): do sort stuff here // sort by order ABC
case(132): do sort stuff here // sort by order ACB
case(231): do sort stuff here // sort by order BCA
/* and so on */
}

我怎样才能轻松做到这一点?

希望这能清楚地解释我想要做什么。如果不是,我非常愿意澄清:)

最佳答案

利用只有 3 个可能的项目这一事实,这比使用比较器可以更有效地完成。我认为编程也稍微容易一些。这是一个如何编写它的示例(未经测试)。

public void sortBy(int sortOrder) {
// Step 1: Divide the items into 3 groups
List<List<MyItem>> groups = Arrays.asList(new ArrayList<>(), new ArrayList<>(), new ArrayList<>());
for (MyItem item : list)
groups.get(item.itemType).add(item);

// Step 2: Use a string to represent the order (ugly, but works)
String order = String.valueOf(sortOrder);

// Step 3: Put the three groups back into the list in the correct order.
int index = 0;
for (char c : order.toCharArray())
for (MyItem item : groups.get(c - '1'))
list.set(index++, item);
}

关于java - 按对象的属性或方法*但按不同的排序顺序 = ABC、BCA、CAB 等对数组列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46632433/

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