【发布时间】:2017-10-02 18:17:18
【问题描述】:
我已经制作了一些具有整数属性的对象,该属性依赖于另一个类生成的另一个对象。我还制作了一个比较器,根据该属性在ArrayList 中对它们进行排序。但是,当我使用此比较器进行排序时,它似乎会立即恢复到初始顺序。这是一个使用我编写的比较器的狗和品种的示例:
public static Comparator<Breed> BreedSizeComparator = new Comparator<Breed>() {
@Override
public int compare(Breed o1, Breed o2) {
int pos1 = o1.getBreedSize();
int pos2 = o2.getBreedSize();
return pos1 - pos2;
}
};
然后我尝试创建一个总是返回第二大品种的方法:
public static Party getSecBigBreed() {
Collections.sort(breeds, BreedSizeComparator);
return breeds.get(1);
}
当我调用它时,虽然我得到了最初位于数组列表中位置 1 的品种(在我进行排序之前)。从我所做的研究来看,这似乎与我将创建的所有品种的数组列表作为品种的类变量这一事实有关。例如。 Breed 类是这样的:
public class Breed {
private int size = 0;
private int type;
private static ArrayList<Breed> breeds = new ArrayList<Breed>();
public Breed(int type0) {
type = type0;
breeds.add(this);
}
我还在这个品种类中创建了一个方法,将一个添加到我每次制作该类型狗时使用的大小,另一个根据其类型获取品种,以及获取方法品种大小:
public void increaseSize() {
this.Size++;
}
public static Breed getBreed(int type0) {
for(int i = 0; i < breeds.size(); i++) {
if(type0 = breeds.get(i).type) {
return breeds.get(i);
}
}
}
public int getBreedSize() {
return size;
}
这是我的狗类:
public class Dog {
private int type;
private int dogNumber;
private static ArrayList<Dog> dogs = new ArrayList<Dog>();
public Dog(int type0) {
type = type0;
getBreed(type).increaseSize();
}
真的不明白为什么当我根据品种的大小对ArrayList 品种进行排序时,它会恢复到原始排序。
【问题讨论】:
-
"
if(type0 = breeds.get(i).type) {" 并且循环后没有返回意味着此代码无法编译。请发帖minimal reproducible example。 -
遵循您的代码真的很难,而且很难隔离问题。我建议您使用调试器并逐步执行代码以找到罪魁祸首。如果订单确实回落(
private static ArrayList<Breed> breeds看起来像是在这里看到的臭候选人,尤其是当您有很多 Dog/Breed 实例时),您会立即看到它逐步通过。