I need to create a java.util.Enumeration
of Fruit objects so that I can pass it to this method during my test. It's a legacy code and I cannot change method signature.
public void get(Enumeration<Fruit> fruits){}
My fruit class:
public class Fruit{
String name;
//getters and setters
}
How can I create an Enumeration of Fruit objects?
In C programming, an enumeration type (also called enum) is a data type that consists of integral constants. To define enums, the enum keyword is used. enum flag {const1, const2, ..., constN}; By default, const1 is 0, const2 is 1 and so on.
An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).
The Enumeration Interface defines the functions by which we can enumerate the elements in a collection of elements.
10) You can not create an instance of enums by using a new operator in Java because the constructor of Enum in Java can only be private and Enums constants can only be created inside Enums itself. 11) An instance of Enum in Java is created when any Enum constants are first called or referenced in code.
You can use the Collections.enumeration(Collection<T>)
method to convert a collection, such as a List<Fruit>
, to Enumeration<Fruit>
:
List<Fruit> fruits = new ArrayList<>();
fruits.add(new Fruit());
Enumeration<Fruit> fruitEnumeration = Collections.enumeration(fruits);
You can use Collections.enumeration()
to convert from a Collection<T>
(which includes List<T>
) to an Enumeration<T>
. An example (blatantly stolen from here):
package com.tutorialspoint;
import java.util.*;
public class CollectionsDemo {
public static void main(String args[]) {
// create an ArrayList
List arrayList = new ArrayList();
// populate the list
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
// create an Enumeration
Enumeration e = Collections.enumeration(arrayList);
System.out.println("Printing the enumeration:");
while (e.hasMoreElements()) {
System.out.println("Value is: " + e.nextElement());
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With