1

This is my first time working with generics, so I'm a little unfamiliar with the terminology. Anyway, supposing I'm creating my own implementation of AbstractList:

class MyList<T> extends AbstractList<T>

And I've got the following three classes that I cannot change:

 class TestNumber class One extends TestNumber class Two extends TestNumber class Three extends TestNumber // etc... 

Is it possible to change the type parameter for MyList to allow only types One and Two, but not other classes that inherit from TestNumber?

2
  • 1
    Create a dummy interface, have only One and Two implement it, and use it as generic type. See docs.oracle.com/javase/tutorial/java/generics/bounded.html Commented Jan 7, 2015 at 4:59
  • @PM77-1 what if i wasn't allowed to change those classes? i forgot to mention this crucial bit earlier, sorry. Commented Jan 7, 2015 at 5:07

1 Answer 1

1

It is not possible to restrict T to being one of One or Two. However you can do something very similar.

Make a class NumberType with exactly two instances, like this:

public final class NumberType<T extends TestNumber> { public static final NumberType<One> ONE = new NumberType<One>(); public static final NumberType<Two> TWO = new NumberType<Two>(); private NumberType() {} } 

Then make your class MyList look like this:

public class MyList<T extends TestNumber> extends AbstractList<T> { public static <T extends TestNumber> MyList<T> newInstance(NumberType<T> type) { return new MyList<T>(); } private MyList() {} // Class body omitted } 

Because the constructor of MyList is private, the only way to instantiate a new MyList is to use the static newInstance() method. The code to instantiate a MyList looks like this:

List<One> list1 = MyList.newInstance(NumberType.ONE); List<Two> list2 = MyList.newInstance(NumberType.TWO); 

It is not possible to instantiate a MyList<Three>.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.