I am implementing a priority queue of custom objects. The custom object class looks like below,
would it be recommended to implement it as a generic class, where T simply is a payload associated with the messageId?
public class PriQMsgPayload <T> implements Comparable<PriQMsgPayload<T>>{
private Integer mMsgNum;
private T ExtraDataForMsg = null;
public PriQMsgPayload(T extra, PluginConfig.PriQMessage msg)
{
mMsgNum= msg;
ExtraDataForMsg = extra;
}
@Override
public int compareTo(PriQMsgPayload<T> another) {
return mMsgNum.compareTo(another.mMsgNum);
}
}
My doubt: in below mentioned case, I first insert the P1 specialized for Integer and when I insert another object P2 which is specialized for MyClass, would the comparator not get confused?
PriQMsgPayload<Integer> P1 = new PriQMsgPayload<Integer>(2, 1);
PriQMsgPayload<MyClass> P2 = new PriQMsgPayload<MyClass>(new MyClass(), 2);
I don’t think there’s any point. The problem comes when you try to put the objects into the queue – there is no fully-cooked type that the queue can have which allows it to contain both of these!
Consider:
You can put them into a queue of this type (i initially said you couldn’t, but @newacct kindly corrected me):
But that involves throwing away the type information about what kind of extra data you have.
None of the queue types which let you add both objects preserve the type of the extra data; that means that when you got the objects out again, you would have lost all type information. There’s no way to write code that safely extracts the object as a
PriQMsgPayload<Integer>rather than aPriQMsgPayload<MyClass>.