Klausos Klausos
Klausos Klausos

Reputation: 16050

Size of HashMap

How to get the number of time windows in the below example? Currently it says that there are 2 time windows, though there are 3 time windows, each defined by open and close times.

    Map<String, String> _timeWindows = new HashMap<String, String>();
    _timeWindows.put("open", "123");
    _timeWindows.put("close", "124");
    _timeWindows.put("open", "523");
    _timeWindows.put("close", "524");
    _timeWindows.put("open", "823");
    _timeWindows.put("close", "824");

    System.out.println(_timeWindows.size());

Upvotes: 0

Views: 112

Answers (4)

arjacsoh
arjacsoh

Reputation: 9232

Since keys are unique in Map when you put "open" and "close" more than one time, it merely ovverides the old values and it keeps the same key. So, correctly it has only two elements with keys: "open", "close".

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213223

A HashMap contains unique keys. So when a new key is inserted, which already exists, it overwrites it's corresponding value. So, your map currently has just 2 key-value pairs.

Given your question, I guess you need a Window class, with type as enum, and the value as String:

class Window {
    private String value;
    private WindowType type;

    enum WindowType {
        OPEN, CLOSED;
    }

    // constructor, getters.
}

and then maintain a Set<Window> or List<Window> depending upon your requirement.

If your value denotes time, then you should really store it as time, and not String. I would suggest to use Joda Time

Upvotes: 1

newuser
newuser

Reputation: 8466

The keys are unique in all maps.

if you want to add more than one value using same key. Use MultiMap

 MultiMap timeWindows = new MultiValueMap();
        timeWindows.put("open", "123");
        timeWindows.put("close", "124");
        timeWindows.put("open", "523");
        timeWindows.put("close", "524");
        timeWindows.put("open", "823");
        timeWindows.put("close", "824");

        System.out.println("timeWindows : "+timeWindows);

output : timeWindows : {open=[123, 523, 823], close=[124, 524, 824]}

Upvotes: 1

rajesh
rajesh

Reputation: 3407

Keys are unique in HashMap. It will have only these values:

_timeWindows.put("open", "823");
_timeWindows.put("close", "824");

Upvotes: 0

Related Questions