Q1. What do you know about Java enums.
Ans.
1. This is automatically inherited from java.lang.Enum and hence, this can't extend any other class. However, Enum can implement interfaces.
2. Enum class is made as final implicitly and hence can't be inherited further.
3. Since it inherits java.lang.Enum, which implements interfaces Comparable and Serializable, enum class has compareTo() method and can be serialized.
4. Also, methods like equals(), hashcode() are automatically created for you.
5. Method ordinal() produces an int indicating the declaration order of each constant.
6. Enum constants are the first thing defined in Enum. Java forces you for same, as compiler gives an error otherwise.
7. Enum class can have methods. And if you have methods, you MUST end the sequence of enum instances with a semicolon.
8. Usually enums have to be qualified with type (i.e should be Color.Red and not Red). However, in Switch case statements, you can use them directly w/o qualifying.
public class Weather {
public enum Season {WINTER, SPRING, SUMMER, FALL};
private final Season season;
private static final List<Weather> listWeather = new ArrayList<Weather> ();
private Weather (Season season) { this.season = season;}
public Season getSeason () { return season;}
static {
for (Season season : Season.values()) { //using J2SE 5.0 for each loop
listWeather.add(new Weather(season));
}
}
public static ArrayList<Weather> getWeatherList () { return listWeather; }
Ans.
1. This is automatically inherited from java.lang.Enum and hence, this can't extend any other class. However, Enum can implement interfaces.
2. Enum class is made as final implicitly and hence can't be inherited further.
3. Since it inherits java.lang.Enum, which implements interfaces Comparable and Serializable, enum class has compareTo() method and can be serialized.
4. Also, methods like equals(), hashcode() are automatically created for you.
5. Method ordinal() produces an int indicating the declaration order of each constant.
6. Enum constants are the first thing defined in Enum. Java forces you for same, as compiler gives an error otherwise.
7. Enum class can have methods. And if you have methods, you MUST end the sequence of enum instances with a semicolon.
8. Usually enums have to be qualified with type (i.e should be Color.Red and not Red). However, in Switch case statements, you can use them directly w/o qualifying.
public class Weather {
public enum Season {WINTER, SPRING, SUMMER, FALL};
private final Season season;
private static final List<Weather> listWeather = new ArrayList<Weather> ();
private Weather (Season season) { this.season = season;}
public Season getSeason () { return season;}
static {
for (Season season : Season.values()) { //using J2SE 5.0 for each loop
listWeather.add(new Weather(season));
}
}
public static ArrayList<Weather> getWeatherList () { return listWeather; }
public String toString(){ return season;}
//takes advantage of toString() method of Season.
}
Q2. What are the different types of Enum?
Ans.
1. Simple Enum:
public enum Color { WHITE, BLACK, RED, YELLOW, BLUE }
Usage:
Color c = Color.WHITE;
System.out.println(c); -> Prints "WHITE"
System.out.println(c.ordinal()); -> Prints "0"
2. Enum that overrides toString method: A semicolon after the last element is required to be able to compile it.
public enum Color { WHITE, BLACK, RED, YELLOW, BLUE;
//Semicolon (;) is required here.
@Override
public String toString() { //only capitalize the first letter
String s = super.toString();
return s.substring(0, 1) + s.substring(1).toLowerCase();
}
}
}
3. Enum with additional fields and custom constructor: Enum constructors must be either private or package default, and protected or public access modifier is not allowed. When custom constructor is declared, all elements declaration must match that constructor.
public enum Color {
WHITE(21, 0), BLACK(22, 5), RED(23, 3), YELLOW(24, 5), BLUE(25, 7);
private int code;
private int intensity;
private Color(int c) {
code = c;
intensity = i;
}
public int getCode() {
return code;
}
public int getIntensity() {
return intensity;
}
}
4. Enum that implements interfaces: Enum can implement any interfaces. All enum types implicitly implements java.io.Serializable, and java.lang.Comparable.
public enum Color implements Runnable {
WHITE, BLACK, RED, YELLOW, BLUE;
public void run() {
System.out.println("name()=" + name() + ", toString()=" + toString());
}
}
A sample test program to invoke this run() method:
for(Color c : Color.values()) { c.run(); }
OR
for(Runnable r : Color.values()) { r.run(); }
5. Enum that override methods inside enum variables or enum method/Constant Specific methods:
public enum Element{
EARTH, WIND, FIRE {
public String info() {
return "HOT";
}
};
public String info() {
return "element";
}
}
Here enum method info() is overridden inside enum variable FIRE.
Q3. Why enum constants can't be used as method arguments.
Ans. Since each enum constant can have its own behaviour, thus treating Enum class as an interface type, one can implement polymorphic behaviour. However, enum instances can't be treated as class types. This is because each enum constant is a static final instance.
Ex: void foo (Color.RED r) => Having enum instance as an argument is not allowed.
Q4. Explain enum valueOf() method.
Ans. This is a static member of Enum class and produces the Enum instance corresponding to the string name passed to it. This throws an exception, if there is no match.
// Throws IllegalArgumentException if text is not known to enum type :
try {
Color c = Enum.valueOf(Color.class, "WHITE");
}
catch (IllegalArgumentException ex) {
log("WHITE is not a valid Color.");
}
Q5. What do you know about Enum values() method.
Ans. I won't define values() method in my enum class. Neither, it is defined in java.lang.Enum. Then from where does it come?
This is a static method added by compiler. Now, since it is a static method, it's not available to parent class i.e you can't type cast to Enum and then use values() method.
However, if you want to get enum instances from Enum class, please use the Class method getEnumConstants as below:
Enum c = Color.Red;
Set <String> methods;
// methods = c.values(); // Not allowed
methods = c.getClass().getEnumConstants(); //allowed
NOTE: If you are already in a Enum class, you can call values() method directly, i.e. without associating with an enum instance.Ex:
public enum Color
{
RED, WHITE, BLACK;
foreach(Color c: values())
{
System.out.println(c);
}
}
Q5. What do you know about Enum values() method.
Ans. I won't define values() method in my enum class. Neither, it is defined in java.lang.Enum. Then from where does it come?
This is a static method added by compiler. Now, since it is a static method, it's not available to parent class i.e you can't type cast to Enum and then use values() method.
However, if you want to get enum instances from Enum class, please use the Class method getEnumConstants as below:
Enum c = Color.Red;
Set <String> methods;
// methods = c.values(); // Not allowed
methods = c.getClass().getEnumConstants(); //allowed
NOTE: If you are already in a Enum class, you can call values() method directly, i.e. without associating with an enum instance.Ex:
public enum Color
{
RED, WHITE, BLACK;
foreach(Color c: values())
{
System.out.println(c);
}
}
Q6. Define EnumSet.
Ans. The EnumSet is designed for speed, because it must compete effectively with bit flags. Internally, it is represented by (if possible) a single long that is treated as a bit-vector, so it’s extremely fast and efficient. The benefit is that you now have a much more expressive way to indicate the presence or absence of a binary feature, without having to worry about performance. The elements of an EnumSet must come from a single enum.
Ex:
EnumSet<Color.class> set = EnumSet.noneOf(Color.class)
// Here since enumSet is empty, all bits in long would be zero.
set.addAll(EnumSet.of(RED, WHITE));
set.addAll(EnumSet.of(RED, WHITE));
// Now since, 2 enum constants have been added to set, their corresponding bits will be 1 and rest bits will be zero.
EnumSets are built on top of longs, a long is 64 bits, and each enum instance requires one bit to indicate presence or absence. This means you can have an EnumSet for an enum of up to 64 elements without going beyond the use of a single long. If you have more than 64 elements in your enum, it adds another long.
Q7. What are the various methods of EnumSet.
Ans.
1. EnumSet.noneOf(Enum Class) -> Returns an empty EnumSet
2. EnumSet.allOf(Enum Class) -> Returns a EnumSet with all elements from EnumClass
3. EnumSet.of(Enum constant1, Enum constant2, ......) -> Returns selected Enum constants
4. EnumSet.range(Enum constant1, Enum constantN) -> Returns Enum constants whose ordinal value lies b/w constant1 and constantN
5. EnumSet.complementOf(Enum constant1, Enum constant2, ......) -> Returns all constants from Enum class except those specified
1. EnumSet.noneOf(Enum Class) -> Returns an empty EnumSet
2. EnumSet.allOf(Enum Class) -> Returns a EnumSet with all elements from EnumClass
3. EnumSet.of(Enum constant1, Enum constant2, ......) -> Returns selected Enum constants
4. EnumSet.range(Enum constant1, Enum constantN) -> Returns Enum constants whose ordinal value lies b/w constant1 and constantN
5. EnumSet.complementOf(Enum constant1, Enum constant2, ......) -> Returns all constants from Enum class except those specified
Q8. Explain "of" method of Enum class.
Ans. Interesting — the of() method has been overloaded both with varargs and with individual methods taking two through five explicit arguments. This is an indication of the concern for performance with EnumSet, because a single of( ) method using varargs could have solved the problem, but it’s slightly less efficient than having explicit arguments. Thus, if you call of() with two through five arguments you will get the explicit (slightly faster) method calls, but if you call it with one argument or more than five, you will get the varargs version of of(). Notice that if you call it with one argument, the compiler will not construct the varargs array and so there is no extra overhead for calling that version with a single argument.
Q9. Explain EnumMap.
Ans. An EnumMap is a specialized Map that requires that its keys be from a single enum. Because of the constraints on an enum, an EnumMap can be implemented internally as an array. Thus they are extremely fast, so you can freely use EnumMaps for enum-based lookups. You can only call put() for keys that are in your enum, but other than that it’s like using an ordinary Map.
EnumMap<Color,Integer> em = new EnumMap<Color,Command>(Color.class);
Ans. An EnumMap is a specialized Map that requires that its keys be from a single enum. Because of the constraints on an enum, an EnumMap can be implemented internally as an array. Thus they are extremely fast, so you can freely use EnumMaps for enum-based lookups. You can only call put() for keys that are in your enum, but other than that it’s like using an ordinary Map.
EnumMap<Color,Integer> em = new EnumMap<Color,Command>(Color.class);
There is always a key entry for each of the enums, but the value is null unless you have called put() for that key.
Q10. Explain the order of elements in EnumSet and EnumMap.
Ans. Both EnumSet and EnumMap, the order of elements is determined by their order of definition in the enum and not in the order in which they are added.
No comments:
Post a Comment