user1419243
user1419243

Reputation: 1705

How to save a large number of elements in a LinkedHashMap?

I have a large number of elements that I want to save in a LinkedHashMap. The problem is that I have really a large number of elements, i.e. more than the size of the Integer class. Since the size() method of the LinkedHashMap class returns an int, I think that the number of elements in the LinkedHashMap can not exceed the possibility of the int. Is that right? If yes, what can I do?

I should also mention that I actually don't know where exactly the problem is occurring in my code. That is just my guess that the problem is with the size() method of the LinkedHashMap. I just get the same error as here.

Upvotes: 1

Views: 385

Answers (1)

RamV13
RamV13

Reputation: 567

I don't believe it's a good idea to have a Map with such a large number of values but if you really want to go ahead with it, you can override LinkedHashMap and use the BigInteger class to increase the size.

public class MyLinkedHashMap<K,V> extends LinkedHashMap<K,V> {
    BigInteger mySize;

    @Override
    public V put(K key, V Value) {
        if (super.put(key,value) == null) // this will still eventually throw an exception because of the 'size' variable incrementing internally in the HashMap
            mySize.add(BigInteger.ONE);
    }

    @Override
    public V remove(Object key) {
        if (super.remove(key) != null)
            mySize.subtract(BigInteger.ONE);
    }

    @Override
    public int size() {
        throw new UnsupportedOperationException();
    }        

    public BigInteger getSize() {
        return mySize;
    }
}

Note that because you cannot change the return type of the size() method you must create your own size method and variable to retrieve the size of the map.

Additionally, you may actually need to override HashMap itself because its put() method will still increment the existing size variable int value and will eventually cause it to go beyond the range of a Java Integer.

Lastly, just to be clear, this is NOT a good idea at all because there are many pitfalls in trying to repurpose an existing data structure in this manner (e.g. forgetting to override other methods that modify/use the size variable, programmer errors which can harm the validity of the original data structure, or other instance variables/side effects that were never originally intended to handle such large sizes etc.).

Upvotes: 1

Related Questions