-1

I want to create hashMap

private Map<Integer,specificObject> myMap;
myMap = new HashMap <Integer,SpecificObject>(initialCapacity);

is it possible that myMap capacity will remain the same for the entire program? even if we've reached the full capacity.

tit
  • 1
  • What do you expect to happen once you reach capacity? – Sotirios Delimanolis Sep 07 '14 at 05:03
  • Can you fill a bottle with a higher volume of water than the volume of the bottle ? Basically, no. If you want to prevent the capacity to change, you have to keep a number of objects in the HashMap lower than loadFactor * capacity. – Dici Sep 07 '14 at 05:06
  • I don't want its length to be changed.. for example if I reached the capacity I'd like it to throw an exception perhaps.. – tit Sep 07 '14 at 05:11
  • Is it possible to use a regular array? It's size is final and you can access/assign by index – Vince Sep 07 '14 at 08:09

4 Answers4

0

You can write a method which checks the current size of hashmap and throw a custom exception if the size is greater than n , where n is the max capacity you want.

Now, in the code add a call to above method before you write map.put.

This will ensure that you dont add elements to map when it exceeds your custom limit.

user2254601
  • 164
  • 2
  • 8
0

You can implement such a class yourself. (The obvious approach would be to create a wrapper class for HashMap that checked the map's size, etcetera each time you called put.)

However, the regular HashMap class doesn't work that way. And furthermore, the initialCapacity parameter is:

  • not the map's size,
  • not the actual number of entries1 you can store before the map needs to be expanded, and
  • not exposed via an accessible variable or getter.

1 - That number is determined by a formula involving the initial capacity and the load factor.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

First, the initialCapacity is not the real capacity.

When you pass 12, the capacity is 16, which means that you pass a, the system will use b >= a and mostly reaching 2^N.

Second, in hashmap, there is a factor = most num / all capacity. For example, if factor = 0.5, and the capacity is 16, when you put 8 objects, the size will extending automatically.

chenzhongpu
  • 6,193
  • 8
  • 41
  • 79
0

While the Java standard library does not have a size limiting cache implementation, Google's Guava has such a class. Take a look at https://code.google.com/p/guava-libraries/wiki/CachesExplained#Size-based_Eviction. Cache has the same interface as a Map with additional functionality like size limiting, timeout on entries, etc that can be defined when creating the cache.

Ravi Kiran
  • 1,139
  • 6
  • 10