javaLearner.java
javaLearner.java

Reputation: 2541

Java queue and multi-dimension array

First of all, this is my code (just started learning 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"); // where 1 is integer

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.

If this cant be done, what else in java classes that can handle this? 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.

[Note]

Please don't give me links that ask me to read java docs. 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.

Upvotes: 1

Views: 3539

Answers (4)

Cagan Sevencan
Cagan Sevencan

Reputation: 11

I think what you are asking for is LinkedHashMap which is a combination of a Queue and a HashMap. While you are able to store the key and value pairs, it would also remember the order like Queue does. 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.

Upvotes: 0

andyczerwonka
andyczerwonka

Reputation: 4260

I think you're asking for a dictionary type in 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.

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

Value in this case will return 1.

Is that what you want?

Upvotes: 1

polygenelubricants
polygenelubricants

Reputation: 384006

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

  • Put the keys (e.g. "a", "b") into the Queue<K>
  • Assign the mapping of the keys to values (e.g. "a"=>3) in the Map<K,V>

Upvotes: 2

pajton
pajton

Reputation: 16246

You want to use a HashMap instead of LinkedList. HashMap is a dictionary-like structure that allows you to create associations, for instance a=>1.

Check out JavaDocs for HashMap to get a grasp how to use it:-).

Upvotes: 1

Related Questions