简体   繁体   中英

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. 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.

I don't know how to implement this by modifying the parameters of the enum class Character . Any help will be appreciated.

Contrary to what you might feel, enum instances are not immutable. Just modify the item field of the enum:

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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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