FreddyK FreddyK - 9 months ago 52
Java Question

Java HashMap of Vectors

i'm in a situation in which i'd like to have an hash map with an Integer value as key and an array of Double as values (of which i know the length).
So i want to have something like

HashMap<Integer, Double[]> hash = new HashMap<Integer, Double[]>();

Next i scan a ResultSet finding key,value for the first attribute.
At the end of this first phase i will have an hash map with some keys and for each key i will have a Double value representing a particular score.

Next i want to scan another different ResultSet with different key,values and i want to populate my hash with these values.
The problem is that here i can find element for which i don't have an entry and documents for which i already have an entry.

I'd like to arrive to a situation in which for a particular key i can access all different scores.

How can i add iteratively values to those arrays? because if i use the usual
i have to use a Double[] as value but i want to add to the hash map different score iteratively.

I think that using a Vector can bring me some problems due to the fact that some keys can have some empty values for which they don't will be populate.


I’m uncertain how well I understand your requirements. I think you may do something sort of:

    double[] arrayInMap = hash.get(key);
    if (arrayInMap == null) {
        hash.put(key, valuesToAdd);
    } else {
        if (arrayInMap.length != valuesToAdd.length) {
            throw new IllegalStateException("Key "+ key + ": cannot add " + valuesToAdd.length
                    + " values to array of length " + arrayInMap.length);
        for (int ix = 0; ix < arrayInMap.length; ix++) {
            arrayInMap[ix] += valuesToAdd[ix];

I hope you’ll at least be able to use it as inspiration.