简体   繁体   English

Java中具有不同数据类型的队列

[英]A queue with different data types in java

I want to implement a FIFO queue with containing different data types in java. 我想在Java中实现一个包含不同数据类型的FIFO队列。 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?? 我只需要将String和String数组存储在队列中即可。

thanx 谢谢

Remember that arrays are java.lang.Objects in Java. 请记住,数组是Java中的java.lang.Objects。 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. 请记住,尽管如此,然后可能需要使用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. 您最好使所有条目都为字符串数组,而仅使大小为1的单个字符串数组更好。这样一来,您的迭代逻辑就变得更加容易。

    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. 否则,请创建一个不可变的类来封装Queue可以接受的其他类型,以及每种应接受的类型的不同构造函数。 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 . 正如@Melv指出的那样,您可以简单地使用Queue of Objects

But using Objects means giving up the type safety and being forced to use the instanceof operator. 但是使用Objects意味着放弃类型安全性并被迫使用instanceof运算符。 an alternative can be to use a Queue<String[]> instead. 另一种选择是改为使用Queue<String[]> Whenever you need to insert a single String , you can just push a single element String array (ie Queue.offer(new String[]{element}) ). 每当您需要插入单个String ,您都可以推入单个元素String数组(即Queue.offer(new String[]{element}) )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM