Element stack
It seems to defeat the purpose of generics , but here it goes:
Stack<Object>s = new Stack<Object>();
s.add("hello");
s.add(1); // int is autoboxed to Integer
The catch will be that when extracting Object
from Stack
it will take some effort to figure out what type of each item is - this will require using instanceof
typecasts as well:
while (!s.isEmpty()) {
Object e = s.pop();
if (e instanceof String)
System.out.println("String: " + (String)e);
else if (e instanceof Integer)
System.out.println("Integer: " + (Integer)e);
else
System.out.println("Other type: " + e);
}
And now we have something that looks like fragile pre-Java code 5 days before generics are added to the language.
a source to share
Typically, you need to solve this using inheritance. It is possible to use the marker interface:
interface MyMarker
{
}
class Foo implements MyMarker
{
}
class Bar implements MyMarker
{
}
Interfaces are practical in such cases because you can implement an unlimited number of interfaces in a single class, and you can add additional interfaces anywhere in the hierchy class.
Then you can put Foo and Bar on the same stack:
Stack<MyMarker> s = new Stack<MyMarker>();
s.add(new Foo());
s.add(new Bar());
This is the way, if at all possible. Otherwise, you will have to do it like coobird suggests.
a source to share
The common stack argument must be the common super-type of all run-time types of the element. For completely heterogeneous collections, it Object
is the common super-type of all reference types. So:
Queue<Object> stack = Collections.asLifoQueue(new ArrayDeque<Object>());
stack.add("red");
stack.add(Color.GREEN);
stack.add(stack);
Obviously, when you come to pop these items from the stack, you will need to do instanceof
a route check against the appropriate code (and possibly a throw).
It's probably better to introduce a layer of indirection. Instead of directly enqueueing objects, wrap them with a meaningful object. Checks instanceof
can be replaced by calls to (virtual) methods that perform the required operations. This is what polymorphism should look like.
a source to share