首页 > 解决方案 > java - 如何随机列出位于Java中不同包中的枚举值?

问题描述

如果我有两个类(Character 和 Person)位于同一个包中,一个类(Audit)与 Character 和 Person 位于不同的包中,如何在 Character 和 Person 的枚举中随机列出值?在字符类中,

public abstract class Character{

    private int age;
    private BodyType bodyType;

    public enum BodyType
    {
        AVERAGE,
        ATHELETIC,
        UNSPECIFIED;

    }
    public Character(int age, BodyType bodyType){
        this.age = age;
        this.bodyType = bodyType;
    }

    public int getAge(){
        return this.age;
    }
    public BodyType getBodyType(){
        return this.bodyType;
    }

    public void setAge(int age){
        this.age = age;
    }
    public void setBodyType(BodyType bodyType){
        this.bodyType = bodyType;
    }

}

在 Person 类中,它扩展了 Character

public class Person extends Character{


    private AgeCategory ageCategory;

    public enum AgeCategory
    {
        CHILD,
        ADULT;
    }
    public Person(int age, BodyType bodyType){

        super(age, bodyType);
    }
    public AgeCategory getAgeCategory()
    {
        if (getAge() >=0 && getAge() <=16){
            return AgeCategory.CHILD;
        }

        if (getAge() >=17){
            return AgeCategory.ADULT;
        }
        return ageCategory;
    }

}

在位于不同包中的 Audit 类中,我必须返回字符串。我尝试了以下代码,但这只会导致按顺序枚举。我想在这里做的是我想列出所有枚举值,但以随机顺序排列。

public class Audit{

    public String toString() 
    {       
        String strings = “random enumeration\n”;

        for (BodyType bodyType : EnumSet.allOf(BodyType.class)) {
            strings += bodyType.name().toLowerCase() + ":";
            strings += "\n";
        }

        for (AgeCategory ageCategory : EnumSet.allOf(AgeCategory.class) ) {
            strings += ageCategory.name().toLowerCase() + ":";
            strings += "\n";
        }
        return strings;
    }
}

标签: java

解决方案


这就是EnumSet的行为。

iterator 方法返回的迭代器以元素的自然顺序(声明枚举常量的顺序)遍历元素。

参考这个

或者

尝试

List<BodyType> randomType = Arrays.asList(BodyType.values());
Collections.shuffle(randomType);
for (BodyType type : randomType) {
    System.out.println(type);
}

为了实现这一点[ in your comment - mix of all enum types]:

您的 ENUM 应该共享通用类型并使用 shuffle。

  1. 迭代 BodyType 的 ENUM 并存储在列表中
  2. 迭代 AgeType 的 ENUM 并存储在同一个 List 中
  3. 随机播放
  4. 打印

推荐阅读