Question

I've read that when you define a {Map, Set, Etc} it is good practice use the interface name as so:

Map<Integer, String> map = new LinkedHashMap<Integer, String>();

instead of:

LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();

I'm not sure why this is, but I've put it to practice in hopes I will understand at a later time. Maybe that time has come.

So I create a class that defines one and create a getter for the Map:

class Data{

    private Map<Integer, String> map;

    public Data(){
        map = new LinkedHashMap<Integer, String>();
        //dynamically put some things into the map
    }

    public Map<Integer, String> getMap(){
        return map;
    }

}

Now I come to my first impasse. I can't return a LinkedHashMap, I have to return a Map. So in another class I get that Map

class Foo{

    public Foo{
        Data data = new Data();
        Map<Integer, String> map = data.getMap();
    }

}

  • Can someone explain what is happening to map when it gets passed?
  • Is it still a LinkedHashMap?
  • Is the data changed at all?
  • What would happen to the order of the Map if, after calling getData(), I put something in the Map?
  • Why wouldn't/shouldn't I just define the Map as in the second code snippet?
    Is my method of getting the map done in ignorance?
  • Should I just make map public?

  • Was it helpful?

    Solution

    Now I come to my first impasse. I can't return a LinkedHashMap

    Here's the misunderstanding: you can return a LinkedHashMap, because a LinkedHashMap is a Map, a particular sort of Map, but a Map anyway.

    Can someone explain what is happening to map when it gets passed?

    When it's passed, it is seen as any Map, like incognito, but it remains the same.

    Is it still a LinkedHashMap?

    Yes.

    Is the data changed at all?

    No.

    What would happen to the order of the Map if, after calling getData(), I put something in the Map?

    This is another topic.

    Why wouldn't/shouldn't I just define the Map as in the second code snippet?

    You needn't do that, since a LinkedHashMap is a Map (on the other hand, a Map is not necessarily a LinkedHashMap).

    Is my method of getting the map done in ignorance? Should I just make map public?

    No.

    OTHER TIPS

    You may want your variable to be able do what it needs to do and still be as flexible as possible in the way it does that. So your variable should be of the type that covers all your needed functionality but is as high as possible in hirachy.

    Licensed under: CC-BY-SA with attribution
    Not affiliated with StackOverflow
    scroll top