3

I have a hashmap declared as :

HashMap<String, Double> hm = new HashMap<String, Double>();

I'm declaring a Vector as :

 Vector<String> productList = new Vector<String>();

Now, I'm trying to add the keys into the vector :

  Set set = hm.entrySet();
  // Get an iterator
  Iterator i = set.iterator();
  // Display elements
  while(i.hasNext()) {
     Map.Entry me = (Map.Entry)i.next();
     //System.out.print(me.getKey() + ": ");
     productList.add(me.getKey());
     //System.out.println(me.getValue());
  }

//hm is the HashMap holding the keys and values.

When I compile the code it gives the following error:

ProductHandler.java:52: error: no suitable method found for add(Object)
     productList.add(me.getKey());
                ^
method Collection.add(String) is not applicable
  (argument mismatch; Object cannot be converted to String)

Do we need to convert the values to String type before trying to add it to the vector? Am I missing out on something?

1
  • 2
    You can use Vector<String> productList = new Vector<String>(hm.keySet()); Commented Apr 2, 2016 at 2:43

2 Answers 2

5

First, you can do it in one line with the Vector(Collection<? extends E) constructor and a call to Map.keySet() like

Vector<String> productList = new Vector<>(hm.keySet());

Second, you should prefer an ArrayList1

List<String> productList = new ArrayList<>(hm.keySet());

1Unless you're sharing this list with multiple threads, adding synchronization with a Vector is a cost.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks that worked! Just curious, how does a Vector map the values of a Set after the hm.keySet() returns the keys?
Here it's equivalent to adding all of the elements in the keySet to the Collection.
Got it! Thanks! :)
2

Don't use raw types.

Your code can be much simpler with enhanced for loop :

  for(String key : hm.keySet()) {
     productList.add(key);
  }

or

  for(Map.Entry<String,Double> entry : hm.entrySet()) {
     productList.add(entry.getKey());
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.