BIU
BIU

Reputation: 2430

Java: Adding Elements to Vector From Hashmap Multiple Times

I'm trying to go over a hashmap of rooms in a maze and add ones that are outer rooms to a Vector. Rooms keep getting added multiple times, can anyone help me figure out why?

public void fillOuterRoomVector()
{
    //initialize the vector
    outerRooms = new Vector<Room>();

    //for each one
    for(Entry<String, Room> e : mazeRooms.entrySet()) 
    {
        //if it is outer
        if (e.getValue().isThisAnOuterRoom()==true)
        {
            //add it
            outerRooms.add(e.getValue());
        }
    }
}

EDIT: I checked in the Variables view in Eclipse while I debugged, the rooms really appear only once in mazeRooms and more than once in outerRooms

EDIT: Screenshot from debug screen

Upvotes: 0

Views: 996

Answers (3)

Ted Hopp
Ted Hopp

Reputation: 234847

You can use a HashSet instead of a Vector to ensure that each Room is recorded only once.

Upvotes: 0

Eric B.
Eric B.

Reputation: 24441

Without knowing the data, my guess would be that mazeRooms has the same value with multiple keys. If your need is to have a Collection of non-duplicated data, I would recommend using a Set instead of a Vector.

Upvotes: 1

NPE
NPE

Reputation: 500773

If the same room gets added to outerRooms() more than once, this means that it was present in mazeRooms more than once (with different keys).

Upvotes: 0

Related Questions