Search code examples
javaenumerationlegacy

Create Enumeration of objects


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?


Solution

  • 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);