java - 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;
}
}
解决方案
这就是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。
- 迭代 BodyType 的 ENUM 并存储在列表中
- 迭代 AgeType 的 ENUM 并存储在同一个 List 中
- 随机播放
- 打印
推荐阅读
- html - 如何制作一个按钮来禁用类中的元素
- javascript - 刷新使用 jquery 或 javascript 打开新选项卡的最后一个选项卡
- python - 斐波那契立方体
- python - 如何使用 python-pptx 提取背景图像?
- graphql - 内容标签未在页面上呈现
- ios - 用户默认值不会实例化视图控制器
- r - 捕获之前记录的所有数据
- react-native - React Native 组件不重新渲染
- android - 为什么我无法在 android studio 4.1.3 中更改 Textview 或 Button 颜色
- spring-boot - 使用 stomp websocket 从 Spring Boot 向客户端发送数据