开发者

A queue with different data types in java

I want to implement a FIFO queue with containing different data types开发者_高级运维 in java. Also I need to know whether I can store an array as one of the types inside the queue. Simply what I need is to store Strings and String arrays in the queue.Any help??

thanx


Remember that arrays are java.lang.Objects in Java. So the following works fine:

    Queue<Object> queue = new LinkedList<Object> ();
    queue.add("string0");
    queue.add(new String[] {"string1", "string2"});

Keep in mind though that iterating this collection will then likely require using instanceof. You may be better of making all entries string arrays, and just making the single strings arrays of size 1. That way your iteration logic becomes easier.

    Queue<String[]> queue = new LinkedList<String[]> ();
    queue.add(new String[] {"string0"});
    queue.add(new String[] {"string1", "string2"});
    for (String[] nextArray : queue) {
        for (String nextString : nextArray) {
            System.out.println("nextElement: " + nextString);
        }
    }


Having different types in your data structure will make more difficult and error prone to use it.

In this case is better to have some wrapper that will make all accesses to your work in the same way.

Try to understand better your domain to see you if you have a natural domain class to hold the value in the key. (What do you want to put in the Queue? a Message, a Request, what kind of Message or Request?, etc)

Otherwise create a immutable class to encapsulate the different type your Queue can accept, a different constructor for each type it should accept. If you start to have more behavior to each case Extract Hierarchy is your friend :) This way your domain class can evolve in a natural way.


As @Melv has pointed out, you can simply use a Queue of Objects.

But using Objects means giving up the type safety and being forced to use the instanceof operator. an alternative can be to use a Queue<String[]> instead. Whenever you need to insert a single String, you can just push a single element String array (i.e. Queue.offer(new String[]{element})).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜