Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 374
Nero Avatar asked Aug 07 '15 18:08

Nero


People also ask

How do you create an enumeration?

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.

Can I create an enum object?

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).

Which enumerate the objects within a collection?

The Enumeration Interface defines the functions by which we can enumerate the elements in a collection of elements.

How do I create an enum instance?

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.


2 Answers

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);
like image 122
izstas Avatar answered Sep 21 '22 16:09

izstas


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());
       }
   }    
}
like image 40
James Ko Avatar answered Sep 20 '22 16:09

James Ko