简体   繁体   中英

Passing a List to Enum as parameter

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

private String description;
private Item item;
private float probability;
ArrayList<Item> itemsLaura = new ArrayList<>();
ArrayList<Item> itemsSally = new ArrayList<>();
ArrayList<Item> itemsAndy = new ArrayList<>();
ArrayList<Item> itemsAlex = new ArrayList<>();
/**
 * Constructor initialising description,item and probability.
 */
private Character(String desc, Item it,float moveProbability)
{
    itemsLaura.add(Item.SANDWICH);
    itemsSally.add(Item.CRISPS);
    itemsAndy.add(Item.DRINK);
    itemsAlex.add(null);
    item = it;
    probability =moveProbability;
}

I have the above enum of Character, I need to change it so instead of each character having one Item they have a list of Item. How would I do that?

I have created ArrayLists for each character but I don't know how to pass them as parameters to the enum Character.

Instead of using a List<Item> , you can have a variable amount of Item by using varargs, but first you should swap moveProbability to be the second argument (as the varargs parameter must be the last element). Your signature will end up like this:

private Character(String desc, float moveProbability, Item... items) {
    ...
}

You can then change:

private Item item;

to

private Item[] items;

and have the following within your constructor:

this.items = items;

This will allow your enum values to take multiple Item s:

LAURA("Laura", 0.0f, Item.SANDWICH, Item.DRINK, Item.CRISPS)

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