Vishal Patel
Vishal Patel

Reputation: 1745

Assing multiple enum values to one class property

I have one java class like below:

public class Location 
{
    public String city;
    public String state;
    public String country;
    public enum type{Beach,Forest,Hills,Desert};
}

as above type member is enum type and i want to assign multiple enum values to type proprties like one Location object has more then one type properties like it has Hills as well as Forest.

then how should i have to do it? where to declare enum and how to assign to enum values to one object.

Is it possible to assign to enum values one object without using array?

Upvotes: 0

Views: 1342

Answers (2)

Boris van Katwijk
Boris van Katwijk

Reputation: 3188

You can store them in class variables:

private final Terrain first = Terrain.BEACH;
private final Terrain second = Terrain.DESERT;

Similarly, you can store them in a collection of terrains if that is more appropriate:

private final Set<Terrain> terrains = new HashSet<>(Arrays.asList(Terrain.BEACH, Terrain.DESERT));

Or use an EnumSet:

private final EnumSet<Terrain> terrains = EnumSet.of(Terrain.BEACH, Terrain.DESERT);

On a side note, it is more conventional to declare enumerations in their own file, I have assumed that it will be called Terrain. Also, constants (thus also enum values) are usually written in capital letters.

Upvotes: -1

wero
wero

Reputation: 32980

You need a Collection to store a variable number of values. Since you don't want to have duplicates use a Set. For enums exist java.util.EnumSet which has a compact and efficient way to store multiple values:

public class Location 
{
    public enum Type {Beach,Forest,Hills,Desert};
    public String city;
    public String state;
    public String country;
    public EnumSet<Type> types = EnumSet.noneOf(Type.class); // start with empty set
}

Upvotes: 2

Related Questions