Java implements an efficient example of an enumerated collection of elements

  • 2020-04-01 03:06:31
  • OfStack

Train of thought: you can specify a type for an EnumSet, which is an enumeration class defined in the same package. Enumsets kind add () method is used to add elements, remove USES enumsets class () method to delete elements, use of enumsets complementOf () method to obtain the object of all, using enumsets range of a class () method to obtain the specified range of elements.

The code is as follows:


package cn.edu.xidian.crytoll;
public enum Weeks {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURADAY, SUNDAY
}

EnumSetTest. Java:


package cn.edu.xidian.crytoll;
import static cn.edu.xidian.crytoll.Weeks.MONDAY;
import static cn.edu.xidian.crytoll.Weeks.THURSDAY;

import java.util.EnumSet;

public class EnumSetTest {
    public static void main(String[] args) {
        EnumSet<Weeks> week = EnumSet.noneOf(Weeks.class);
        week.add(MONDAY);
        System.out.println("EnumSet Elements in: " + week);
        week.remove(MONDAY);
        System.out.println("EnumSet Elements in: " + week);
        week.addAll(EnumSet.complementOf(week));
        System.out.println("EnumSet Elements in: " + week);
        week.removeAll(EnumSet.range(MONDAY, THURSDAY));
        System.out.println("EnumSet Elements in: " + week);
    }
}


Run the program and you'll see the results.


Related articles: