简体   繁体   English

在方法中修改枚举参数值

[英]Modifying enum parameter values in a method

Item 项目

public enum Item
{
    SANDWICH("sandwich"), CRISPS("crisps"), DRINK("drink");

private String description;

Item(String description)
{
this.description = description;

}

public String toString()
{
    return description;
}

}

Character 字符

  public enum Character
{
    LAURA("Laura",Item.SANDWICH),SALLY("Sally", Item.CRISPS),ANDY("Andy", Item.DRINK),ALEX("Alex", null);


private String charDescription;
private Item item;

private Character(String Chardescription, Item item) {
    this.charDescription = charDescription;
    this.item = item;
}


public String toString()
{
    return charDescription;
}

public boolean take(Item item)
{

}

I wrote these two enumeration classes, where Item contains items with their descriptions and Character has four different Character objects: LAURA, SALLY, ANDY and ALEX, each parameterized with a description and an item. 我编写了这两个枚举类,其中Item包含带有描述的项目,而Character具有四个不同的Character对象:LAURA,SALLY,ANDY和ALEX,每个对象都带有一个描述和一个项目。 The item may be null. 该项目可以为空。

I need to write a method take(Item item) , which takes the indicated item from the character if the character has that item, and returns true if it is successful in taking the item from the character, and false otherwise. 我需要编写一个方法take(Item item) ,如果字符具有该项目,则从字符中获取指示的项目;如果成功从字符中获取该项目,则返回true;否则返回false。

I don't know how to implement this by modifying the parameters of the enum class Character . 我不知道如何通过修改枚举类Character的参数来实现这一点。 Any help will be appreciated. 任何帮助将不胜感激。

Contrary to what you might feel, enum instances are not immutable. 与您的感觉相反, enum实例不是不变的。 Just modify the item field of the enum: 只需修改枚举的item字段即可:

public boolean take(Item item) {
    if (item == this.item) {
        this.item = null;
        return true;
    }
    return false;
}

Enumeration values are designed as constant values. 枚举值被设计为常量。
Look at the Oracle examples : Day, Planet. 看一下Oracle示例 :Day,Planet。

It is not explicitly said that the enum value states have to be immutable but I find quite counter intuitive to define constant things defined at compile time that have a mutable state. 没有明确地说枚举值状态必须是不可变的,但我发现定义在编译时定义的具有可变状态的常量事物是相当直观的。
Note also that the very most of time, enum values defined in the JDK (or third party libraries) are immutable. 还要注意,在大多数情况下,JDK(或第三方库)中定义的枚举值是不可变的。

Mutability seems really more natural and expected for classes. 可变性似乎真的更自然,并且期望用于类。

So I advise to not change their state after their instantiation. 因此,我建议不要在实例化后更改其状态。
If you need to change their values, using a class makes probably more sense. 如果您需要更改其值,则使用类可能更有意义。

Note that defining reading methods in your enum class such as : 请注意,在您的枚举类中定义读取方法,例如:

public boolean hasItem(Item item){
   return item == this.item;
}

is valid without any hesitation. 毫不犹豫地有效。

我认为您想将角色创建为类,而不是枚举。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM