-5
import java.util.HashMap;
import java.util.TreeMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;

public class Maps {
  public static void main(String[] args) {
    Map mapA = new HashMap();
    Map mapB = new TreeMap();

    mapA.put("key1", "element 1");
    mapA.put("key2", "element 2");
    mapA.put("key3", "element 3");

    // The three put() calls maps a string value to a string key. You can then
    // obtain the value using the key. To do that you use the get() method like this:

    String element1 = (String) mapA.get("key1");
    // why do I need the type cast on the right?
    System.out.println(element1);

    //Another examples with maps
    Map vehicles = new HashMap();
    vehicles.put("BMW", 5);
    vehicles.put("Mercedes", 3);
    vehicles.put("Audi", 4);
    vehicles.put("Ford", 10);

    System.out.println("Total vehicles: " + vehicles.size());

    for(String key: vehicles.keySet())
      System.out.println(key + " - " + vehicles.get(key));
    System.out.println();

    String searchKey = "Audi";
    if (vehicles.containsKey(searchKey))
      System.out.println("Found total " + vehicles.get(searchKey) + " "
        + searchKey + " cars!\n");

    // clears vehicles
    vehicles.clear();

    //should equal to 0 now
    System.out.println("Vehicle now contains this many vehicles :" + vehicles.size());

    // Lets iterate through the keys of this map:

    Iterator iterator = mapA.keySet().iterator();
    System.out.println(iterator);  // How to inspect this? Is it a kind of map?

    Map mapC = new HashMap();
    while(iterator.hasNext()){
      Object key   = iterator.next();
      Object value = mapA.get(key);
      mapC.put(key,value);
    } // Is there a better way to take the contents of the iterator and put them in a new map?
    System.out.println(mapC);
    //create a new hashmap
    HashMap hm = new HashMap();
    // put elements to the map

    hm.put("Zara", new Double(3434.34));
    hm.put("Mahnaz", new Double(123.22));
    hm.put("Ayan", new Double(1378.00));
    hm.put("Daisy", new Double(99.22));
    hm.put("Qadir", new Double(-19.08));

    //get a set of the entries
    // The entrySet( ) method declared by the Map interface returns a Set containing the
    // map entries.

    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.println(i.getClass());  // get the class of i
      System.out.println(i instanceof Iterator); // checks to see if i is of class Iterator
      System.out.print(me.getKey() + ": ");
      System.out.println(me.getValue());
    }
    System.out.println();
    // Deposit 1000 into Zara's account
    double balance = ((Double)hm.get("Zara")).doubleValue();
    hm.put("Zara", new Double(balance + 1000));
    System.out.println("Zara's new balance: " +
      hm.get("Zara"));
  }
}

This is my error:

Maps.java:53: error: incompatible types: Object cannot be converted to String for(String key: vehicles.keySet())

My questions are

  1. Why is that error occurring? Why is an object trying to be converted to a string? I thought I had put strings as keys into the vehicles HashMap. What is going on?

  2. Why is the typecast needed in the line:

     String element1 = (String) mapA.get("key1");
    
Jwan622
  • 11,015
  • 21
  • 88
  • 181
  • Just a bit of guidance, don't use the raw collection. This should resolve most of your worries: Map mapA = new HashMap<>(); – Juned Ahsan Jan 06 '16 at 04:06
  • @JunedAhsan No it won't if you don't declare the generic types for the `mapA` variable. Should be `Map map = new HashMap();`. Or in recent Java versions: `Map map = new HashMap<>();` – Robby Cornelissen Jan 06 '16 at 04:08
  • [This question](http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) and its answers would be a pretty helpful thing for you to read. – resueman Jan 06 '16 at 04:13
  • Let me check this out. I've always been confused what the purpose of this line is: Map map = new HashMap(); – Jwan622 Jan 06 '16 at 16:35

1 Answers1

0
  1. vehicles.keySet() returns a collection of Object, not String. Just because you put strings in as the keys, the API doesn't change. One approach would be:

    for(Object keyObj: vehicles.keySet()) { String key = keyObj.toString(); // or cast to (String)

  2. Same issue - get() returns an Object. Just because you used a string, the API is still just an object. Again either cast or use toString.

As has been hinted in various comments, if you use generics the compiler has a much better idea of "what types are where". If you define your map like Map<String,String> mapA = new HashMap<String, String>(); then your original code may work because the compiler knows what the data types in the map are.

John3136
  • 28,809
  • 4
  • 51
  • 69
  • 1
    Why is everyone that answers this question pretending that generics never happened? – Robby Cornelissen Jan 06 '16 at 04:10
  • @RobbyCornelissen Just answering the OPs question. He didn't use generics, so answering his question in terms of generics makes no sense. Suggesting them as an improved implementation is fine. I'll probably edit to do just that. – John3136 Jan 06 '16 at 04:11
  • Fair point. At first I thought the reason not to use generics was because of the fact that OP is using an old Java version, but since the code includes the enhanced for-loop, we know it's at least Java 5, so a generic map should be the preferred solution. – Robby Cornelissen Jan 06 '16 at 04:15