Even the best planning is not so omniscient as to get it right the first time. Fred Brooks

EnumSet

Language Java | Level Intermediate | Category Java collections framework (JCF) | 2015-07-24 11:11:05

0 Comments


Definition

An EnumSet is a Set which contains enum instance of a specific enum type, in a more efficient way than other Set implementations.

Character

Enumset internally uses bit vector which improve the performance.
It improves the time and space performance.
It does not throw concurrent modification exception.
Enumset is not synchronized.

source Code

								
package com.careerdrill.collections.set;

import java.util.EnumSet;


public class EnumSetUse {
	private enum Languages {
 		C, CPP, JAVA, PERL, PYTHON, JAVASCRIPT, CSHARP;
 
 		public static final EnumSet< Languages > OBJECT_BASED = EnumSet.range(CPP, CSHARP);
 
 		public final boolean isObjectBased() {
 			return OBJECT_BASED.contains(this);
 		}
 
 		public static final EnumSet< Languages > ALL_LANGUAGES = EnumSet.allOf(Languages.class);
 	}

	


	public static void main(String[] args) {
	
		 
 		for (final Languages lan : Languages.ALL_LANGUAGES)
 			System.out.println(String.format("%d. %s " + (lan.isObjectBased() ? "Object Oriented language" : "Procedural language") + ".", lan.ordinal() + 1, lan));
 
 		System.out.print("I know ");
 
 		System.out.println(Languages.OBJECT_BASED.containsAll(Languages.ALL_LANGUAGES) ? "Procedural  and Object Oriented languages." : "Only Object Oriented languages.");
 
 		final EnumSet< Languages > weekend = Languages.ALL_LANGUAGES.clone();
 		weekend.removeAll(Languages.OBJECT_BASED);
 
 		


	}

}
						

Output

    					 
1. C Procedural language.
2. CPP Object Oriented Language.
3. JAVA Object Oriented Language.
4. PERL Object Oriented Language.
5. PYTHON Object Oriented Language.
6. JAVASCRIPT Object Oriented Language.
7. CSHARP Object Oriented Language.
I know Only Object Oriented languages.
    					 
					    

Comparison

EnumMap EnumSet
All basic operations execute in constant time. All basic operations execute in constant time.
Faster than Hashmap. Faster than hash set.
Enum maps are represented internally as arrays. Represented internally as bit vectors.
Bulk operation executes in constant time. Bulk operation executes in constant time.

When to use

When you don't want duplicate elements, you can use EnumSet.

0 Comments



Please login to add comments.