java中的enumset小结

java中的enumset其实是set的一个实现类了,但平常比较少用到,所以小结归纳下:

1 先定义一个枚举
  public enum Seasons {
    AUTMN,WINTER,SPRING,SUMMER
}

   测试:
 public static void main(String[] args) {
        EnumSet<Seasons> coldSeasons = EnumSet.of(Seasons.AUTMN, Seasons.WINTER);
        for (Seasons seasons : coldSeasons) {
            System.out.println("SEASON:"+seasons.name());
        }
       
    }
        


   使用of方法创建新的enumset,并且可以遍历,输出:
  SEASON:AUTUMN SEASON:WINTER

2 allOf 输出所有枚举元素
 

     EnumSet seasons = EnumSet.allOf(Seasons.class);
        for (Seasons season : seasons) {
            System.out.println("SEASONS:"+season.name());
        }



    SEASONS:AUTUMN SEASONS:WINTER SEASONS:SPRING SEASONS:SUMMER

3 Enuset.noneOf 输出空的

4  rangeOf包括起和始的范围
  
 public static void main(String[] args) {
        EnumSet seasons = EnumSet.range(Seasons.AUTUMN,Seasons.SPRING);
        for (Seasons season : seasons) {
            System.out.println("SEASONS:"+season.name());
        }



  输出:SEASONS:AUTUMN SEASONS:WINTER SEASONS:SPRING

5 complementOf方法,排除某个元素,比如
  
 EnumSet seasons = EnumSet.range(Seasons.AUTUMN,Seasons.SPRING);
        for (Seasons season : seasons) {
            System.out.println("SEASONS:"+season.name());
        }
        EnumSet complementEnumset = EnumSet.complementOf(seasons);
        for (Seasons season : complementEnumset) {
            System.out.println("SEASON:"+season.name());
        }




结果为:SEASON:SUMMER

你可能感兴趣的:(enumset)