0

Below code comes from Java 11, java.util.ImmutableCollections.java, line 783.

 static final int EXPAND_FACTOR = 2;

 MapN(Object... input) {
            if ((input.length & 1) != 0) { // implicit nullcheck of input
                throw new InternalError("length is odd");
            }
            size = input.length >> 1;

            int len = EXPAND_FACTOR * input.length;
            len = (len + 1) & ~1; // ensure table is even length
            table = new Object[len];

Why the len is twice input.length? I think the table doesn't need to store elements more than input.length.

Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55
Raines
  • 9
  • 2
  • 1
    For a map to prevent collisions there should be some room. `input.length*3/4` would need two constants for integer arithmetic, so 2 is neat for lazy programming. – Joop Eggen Jan 07 '20 at 11:26
  • Same reason any typical hash table has a load factor, immutable or not. – user2357112 Jan 07 '20 at 11:30
  • `*3/4`? That would mean trying to fit 8 elements in an array of size 6. – kaya3 Jan 07 '20 at 11:30
  • It's possible that the load factor answer is correct, but this class is intended for small maps afaik so it may just be an unsorted array instead of a hashtable - someone will need to check. (I can't check the source myself right now.) Also I would expect the constant to be named LOAD_FACTOR in that case. – kaya3 Jan 07 '20 at 11:34
  • 2
    @kaya3: I checked. The (unposted) comment right above the `EXPAND_FACTOR` declaration explicitly says it's for a load factor. The OP really should have read that comment, or at least posted it. – user2357112 Jan 07 '20 at 12:26
  • I see, nice one. – kaya3 Jan 07 '20 at 12:57

0 Answers0