Question

My textbook barely talks about enumeration in Java, and the videos that I've watched don't explain much. So from what I'm understanding, enumeration is like a whole different class where you can store constants in. Can someone expand to me about the constants and perhaps show me better examples? Like I understand what constants are after seeing the examples such as colors, directions, and in the previous videos it was people, while in the enum version of one my projects during the school year, it was command words. But I don't 100% understand the concept or how to use.

  1. Also, what's the point of an Enumeration when you can just make a collection? Like for instance, the last video i saw, the video maker made enums of people in the format of name(String description, int age), and that's how he defined his constructor and he had get and set methods. What's the advantage of doing this rather than just creating a person object in the same exact way and them creating a collection and storing person objects in there?

  2. I went to look up the above, and after seeing this thread: Difference between Java Enumeration and Iterator An iterator is something that will let me loop through a collection, and all this time I thought enumeration was something like a different class. But in the thread they're comparing them. Enumeration is just something like an iterator, but without the remove method. Is this enumeration something different than what I was talking about above?

Was it helpful?

Solution

You are confused between several different classes.

  1. enum
  2. Enumeration
  3. Iterator

An enum is an enumerated constant, i.e. a constant that can take several defined values such as

public enum Gender {
    MALE,
    FEMALE;
}

It is designed to provide type safety.

An Enumeration is a now deprecated part of the Collections API - forget about this. It is superseded by Iterator.

An Iterator is an implementation of the Iterator Pattern as described by the Gang of Four.

For why to use an Iterator rather than a Collection maybe my answer here will help.

As for enums of people in the format of name(String description, int age), and that's how he defined his constructor and he had get and set methods. This is a big no-no.

An enum should be a constant so should not have setter methods. An enum is a set of defined values like in my example above.

If you want a Collection of people then a Person class in a Collection<Person> would be the correct solution.

So, in summary. Use an enum for constant values; use a Collection for, well, collections of things. And do not use an Enumeration - forget it exists at all.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top