Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

generic class using enum?

Status
Not open for further replies.

kaijanm

Programmer
May 14, 2003
102
0
0
US
I'm relatively new to Java and I'm trying to refactor some code I wrote to make it more generic.

I currently have several classes that are basically exactly the same except they each have a different enum. For instance, I have an A class that stores values for AData1, AData2, AData3. I also have a B class that stores values for BData1 and BData2. I have an enum of AData1, AData2, AData3 and another enum of BData1 and BData2.

The classes have essentially the same methods, but the only difference is their enum.

I was hoping to create a generic class and then simply pass in the enum to a constructor on an instance. I'm thinking I can use an EnumMap to store the values I need. I can't figure out how to pass in an entire enum to a function. I can pass in one value from the enum, but not the entire thing. Any ideas?
 
I don't know how to avoid -Xlint:unchecked warnings, but this compiles and runs - maybe it helps?
Code:
 import java.util.*;
	
enum Ad1 
{
	foo, bar, foobar;
}

enum Ad2 
{
	foofoo, barbar;
}

enum Bd1 
{
	f, b, fb;
}

class Store <E extends Enum <E>>
{
	private EnumMap <E, String> em;
		
	public Store (EnumMap <E, String> em) 
	{
		this.em = em;
	}
	
	public void put (E e, String v)
	{
		em.put (e, v);
	}
	
	public void show () 
	{
		for (Map.Entry<E, String> entry : em.entrySet ()) 
		{
			System.out.println ("Map entry: " + entry);
		}
	}
}

public class ABstore  <E extends Enum <E>>
{
	public static void main (String [] args) 
	{
		EnumMap ma1 = new EnumMap (Ad1.foo.getClass ());
		EnumMap <Ad2, String> ma2 = new EnumMap (Ad2.foofoo.getClass ());
		EnumMap <Bd1, String> mb1 = new EnumMap (Bd1.f.getClass ());
		Store <Ad1> a1s = new Store <Ad1> (ma1);
		Store <Ad2> a2s = new Store <Ad2> (ma2);
		Store <Bd1> b1s = new Store <Bd1> (mb1);
		
		a1s.put (Ad1.foo, "7");
		a1s.put (Ad1.bar, "9");
		a1s.put (Ad1.foo, "3");

		a2s.put (Ad2.foofoo, "foofoo");
		a2s.put (Ad2.barbar, "barbar");
		a2s.put (Ad2.barbar, "barefoot");
		
		b1s.put (Bd1.f, " f ");
		b1s.put (Bd1.b, " b ");
		b1s.put (Bd1.fb," fb ");
		
		a1s.show ();
		a2s.show ();
		b1s.show ();		
	}
}

don't visit my homepage:
 
I'm going to play with this a bit, and then I'll likely have more questions! Thanks!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top