gpt4 book ai didi

Java 多数组排序

转载 作者:行者123 更新时间:2023-12-01 22:37:36 26 4
gpt4 key购买 nike

嗨,我目前有 4 个数组都保存着不同的数据,我遇到的问题是我想按字母顺序对其中一个数组进行排序,通常我会这样做

class IgnoreCaseComparator implements Comparator<String> {
public int compare(String strA, String strB) {
return strA.compareToIgnoreCase(strB);
}
}
IgnoreCaseComparator icc = new IgnoreCaseComparator();
java.util.Collections.sort(ARRAY,icc);

其中 ARRAY 是我想要按字母顺序排序的数组,但我需要将数组一起排序。

例如,假设我的数组如下所示

Pet Array: [Dog, Cat, Bird]
Owner Array: [Jim, Kyle, Joe]
Friend Array: [Jake, Jim, John]
Cat Array: [false, true, false]

我想根据宠物数组进行排序,我的输出应该是这样的,其中所有第三个值现在都是第一个,第一个值现在都是第三个(这过于简化了,我的实际数组包含数千个输入)

Pet Array: [Bird, Cat, Dog]
Owner Array: [Joe, Kyle, Jim]
Friend Array: [John, Jim, Jake]
Cat Array: [false, true, false]

有没有一种简单的方法可以做到这一点,我可以对一个数组进行排序并让其他数组遵循。感谢您对这个问题的任何帮助。

===编辑===

除了我的解决方案略有不同之外,因为我做了一些阅读,检查的答案是完美的,我在compareTo方法中只有一个稍微不同的返回行

    class Entity implements Comparable<Entity> {
String Pet;
String Owner;
String Friend;
int Cat;

Entity(String Pet, String Owner, String Friend, int Cat) {
this.Pet = Pet;
this.Owner = Owner;
this.Friend = Friend;
this.Cat = Cat;
}

@Override
public int compareTo(Entity other) {
return this.Pet.compareToIgnoreCase(other.Pet);
}
}

最佳答案

您可以声明一个对象:

class Entity implements Comparable<Entity> {
Pet pet;
Person owner;
Friend friend;
boolean cat;

Entity(Pet pet, Person owner, Friend friend, boolean cat) {
this.pet = pet;
this.owner = owner;
this.friend = friend;
this.cat = cat;
}

public int compareTo(Entity b) {
return pet.getName().compareToIgnoreCase(b.pet.getName());
}
}

然后构建这些对象的数组或列表。以及排序。

Entity[] array = new Entity[pets.length];
for (int i = 0; i < pets.length) {
array[i] = new Entity(pets[i], owners[i], friends[i], cats[i]);
}
Arrays.sort(array);

之后您可以将其拆分回数组。

for (int i = 0; i < pets.length) {
pets[i] = array[i].pet;
owners[i] = array[i].owner;
...
}

关于Java 多数组排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10182462/

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