枚举列表:我有2个枚举,我必须创建一个列表/数组

时间:2014-09-13 00:36:45

标签: java arrays arraylist enums enum-map

相当新手问题我想但是我花了6个多小时做这种方式和另一种方式而且我不知道最好的做法是什么,所以我要求你提供关于如何做到这一点的帮助

我有2个枚举,例如汽车和自行车。我必须让listarray(我不知道哪个更好)内部有2 - 1 000 000个元素,当它完成时我必须重新排序list / { {1}}(开头的自行车和最后的车)。只有一辆自行车和一辆车,但可能有数百或者更多,甚至更多。我不知道是否可以使array约2个枚举。

EnumMap有关键和值,所以我给了键“car”和值“0”,键“自行车”值“1”,所以重新排序会更容易,但我发现我可以不要在EnumMap上执行此操作,因为无论我添加多少元素,总是只有2,自行车和汽车。我不能谈论数以百计。

我没有专注于数组的原因是在代码的开头有EnumMap

这是功课是的,但我只是希望找到实现它的方法(花费数小时阅读并尝试不同的方法),而不是有人为我做。

3 个答案:

答案 0 :(得分:1)

好的,根据我的理解。您需要List Animals,并实施方法public static void reorder(ArrayList<Animal> animals)以重新排序此列表。

这就是我的想法:

public class EnumHw {

    public static void main(String[] args) {
        ArrayList<Animal> animalList = new ArrayList<Animal>();

        animalList.add(Animal.GOAT);
        animalList.add(Animal.SHEEP);
        animalList.add(Animal.GOAT);
        animalList.add(Animal.SHEEP);

        EnumHw.reorder(animalList);

        for (Animal animal : animalList) {
            System.out.println(animal);
        }
    }

    public static void reorder(ArrayList<Animal> animals) {        
        Collections.sort(animals);        
    }
}

enum Animal {
    //Order you enum in the way you want them to come first in the List
    GOAT,
    SHEEP;    
}

希望它能为您提供帮助(并允许您使用Collections API。:)

答案 1 :(得分:1)

我建议你将逻辑拆分为两种方法,首先是countGoats(Animal[]) -

private static int countGoats(Animal[] animals) {
    int count = 0;
    for (Animal a : animals) {
        if (Animal.goat == a) {
            count++;
        }
    }
    return count;
}

由于每个goats计数的元素应该是数组中的goat(以及sheep之后的每个元素),我们可以使用类似的方式迭代数组,

public static void reorder(Animal[] animals) {
    if (animals == null) {
        return;
    }
    int goats = countGoats(animals);
    for (int i = 0; i < animals.length; i++) {
        // if (i < goats) - it's a goat, otherwise it's a sheep.
        animals[i] = (i < goats) ? Animal.goat : Animal.sheep;
    }
}

这是Counting sort的示例,运行时复杂度为O(n)。正如维基百科的文章所述,

  

因为计数排序使用键值作为数组的索引,所以它不是比较排序,并且用于比较排序的Ω(n log n)下限不适用于它。

答案 2 :(得分:0)

public void reorder(Animal[] animals) {
    int sheepCount = 0; 
    int goatCount = 0;
    for (Animal oneAnimal : animals) {
        if (oneAnimal == Animal.sheep) {
            sheepCount++;
        } else {
            goatCount++;
        }
    }
    for (int i = 0; i < sheepCount; i++) {
        animals[i] = Animal.sheep;
    }
    for (int i = 0; i < goatCount; i++) {
        animals[i + sheepCount] = Animal.goat;
    }
}