views:

97

answers:

3

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.

+1  A: 

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:-).

pajton
@pajton: While I am reading, could you tell how to to access specific element? Like element 11 of 20?
javaLearner.java
Easy, use `HashMap.get("a")`. You access elements basing on the first side of association (the key), you cannot access them basing on their index (the is no such thing here). But, there is possibility to iterate over a whole collection if you like.
pajton
+1  A: 

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?

arcticpenguin
cool!! Yeah. I think I got it. No need to read the java docs already. Thanks
javaLearner.java
I am checking if I can do push, pop thing in hashmap. brb ^^,
javaLearner.java
+1  A: 

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>
polygenelubricants
@polygenelubricants: brilliant idea. I am trying to write the code now =)
javaLearner.java