Question

How do I use Hashmap with 3 parameters with string, string, int. The first string is a location, the second string is a different location, and the int represents the time from one to the other.

If I make a key posistion1, position3, int it will tell me how much time between position1 and position3.

There is 100 locations and I need to specify the time between all locations.

Was it helpful?

Solution

The simplest way to do this is to use some Pair class (that simply stores two parameters and implements hashCode and equals correctly) as the key of your HashMap. There is an implementation here or you can write your own, more specific to your purpose (with more sensible variable and method names).

OTHER TIPS

A HashMap maps one variable to one other variable. You want to use two variables as a key, so you can make a simple Coordinates class.

class Coordinates {
    final int x;
    final int y;
    public Coordinates(int x, int y) {
        this.x = x;
        this.y = y;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + x;
        result = prime * result + y;
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Coordinates other = (Coordinates) obj;
        if (x != other.x)
            return false;
        if (y != other.y)
            return false;
        return true;
    }
    @Override
    public String toString() {
        return "<"+x+","+"y"+">";
    }
}

In this code, the hashCode and equalsmethods have been generated by Eclipse. All you need to know is that hashCode generates a number which Map uses as identifier for your coordinate and that equals checks if two Coordinates point to the same place.

You can then use a Map<Coordinates,String> for your map. To add something you use:

yourMap.add(new Coordinates(2,3), "A String")

To retrieve something you use

yourMap.get(new Coordinates(2,3)

If I understood correctly, you want to create a map of position1, position2 that holds some attribute of the pair in a map. First, you need to be sure that the map doesn't get too large. 10,000 entries isn't huge for small instances.

Create a PositionPair class that overrides equals() (and hashCode(), because they two need to agree.) You could use the class as the key in a Map, which answers your question.

Or you could simply add the attribute to the class and store instances in a List. If you want to get fancy, don't calculate the time until it is requested the first time, then save it before returning it.

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