简体   繁体   English

Java队列和多维数组

[英]Java queue and multi-dimension array

First of all, this is my code (just started learning java):首先,这是我的代码(刚开始学习java):

Queue<String> qe = new LinkedList<String>();

qe.add("b");
qe.add("a");
qe.add("c");
qe.add("d");
qe.add("e");

My question:我的问题:

  1. Is it possible to add element to the queue with two values, like:是否可以使用两个值将元素添加到队列中,例如:

    qe.add("a","1"); qe.add("a","1"); // where 1 is integer // 其中 1 是整数

So, that I know element "a" have value 1. If I want to add a number let say "2" to element a, I will have like a => 3.所以,我知道元素“a”的值为 1。如果我想在元素 a 上添加一个数字,比如“2”,我会像 a => 3。

If this cant be done, what else in java classes that can handle this?如果不能做到这一点,Java 类中还有什么可以处理这个问题? I tried to use multi-dimention array, but its kinda hard to do the queue, like pop, push etc. (Maybe I am wrong)我尝试使用多维数组,但它有点难以做队列,比如弹出、推送等(也许我错了)

  1. How to call specific element in the queue?如何调用队列中的特定元素? Like, call element a, to check its value.比如,调用元素 a,检查它的值。

[Note] [笔记]

Please don't give me links that ask me to read java docs.请不要给我要求我阅读 Java 文档的链接。 I was reading, and I still dont get it.我正在阅读,但我仍然不明白。 The reason why I ask here is because, I know I can find the answer faster and easier.我之所以在这里问是因为,我知道我可以更快更容易地找到答案。

You'd want to combine a Queue<K> with a Map<K,V> : 您想要将Queue<K>Map<K,V>

  • Put the keys (eg "a", "b" ) into the Queue<K> (例如"a", "b" )放入Queue<K>
  • Assign the mapping of the keys to values (eg "a"=>3 ) in the Map<K,V> Map<K,V>中将映射分配给 (例如"a"=>3

You want to use a HashMap instead of LinkedList . 您想使用HashMap而不是LinkedList HashMap is a dictionary-like structure that allows you to create associations, for instance a=>1. HashMap是一个类似字典的结构,允许您创建关联,例如a => 1。

Check out JavaDocs for HashMap to get a grasp how to use it:-). 查看JavaDocs for HashMap以了解如何使用它:-)。

I think you're asking for a dictionary type in Java. 你要求Java中的字典类型。

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);

You can then access them by key - in this case the String you choose as the key. 然后,您可以通过键访问它们 - 在这种情况下,您选择作为键的String。

int value = map.get("a");

Value in this case will return 1. 在这种情况下,值将返回1。

Is that what you want? 那是你要的吗?

I think what you are asking for is LinkedHashMap which is a combination of a Queue and a HashMap.我认为您要的是LinkedHashMap ,它是 Queue 和 HashMap 的组合。 While you are able to store the key and value pairs, it would also remember the order like Queue does.虽然您可以存储键值对,但它也会像 Queue 一样记住顺序。 The only thing is you'd have to use an iterator since there is no poll() method, however you can visit each element in the order that they were added.唯一的问题是您必须使用迭代器,因为没有poll()方法,但是您可以按照添加的顺序访问每个元素。

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

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