1

I found that EnumMap T[] toArray(T[] var2) have this implementation:

public <T> T[] toArray(T[] var1) {

    int var2 = this.size();

    if (var1.length < var2) {
    var1 = (Object[])((Object[])Array.newInstance(var1.getClass().getComponentType(), var2));
    }

    if (var1.length > var2) {
    var1[var2] = null;
    }

    return (Object[])this.fillEntryArray(var1);
}

I don't understand what is really means:

if (var1.length > var2) {
    var1[var2] = null;
}

If our array for example String[5] and we tries:

enum myKeys{ONE, TWO, THREE};        

EnumMap myEnum = new EnumMap<myKeys, String>(myKeys.class);

myEnum.put(myKeys.ONE, "1");
myEnum.put(myKeys.TWO, "2");
myEnum.put(myKeys.THREE, "3");

final Object[] objects = myEnum.entrySet().toArray(new Object[8]);

for (Object o: objects) {
    System.out.println(o);
}

Output is:

ONE=1
TWO=2
THREE=3
null
null
null
null
null

1) What is the purpose of the design EnumMap T[] toArray(T[] a) instead of toArray()?

2) Why used

if (var1.length > var2) {
    var1[var2] = null;
}

Is it for mark N+1 element is null for the iterator?

Gaurav Jeswani
  • 4,410
  • 6
  • 26
  • 47
Yury Finchenko
  • 1,035
  • 13
  • 19
  • 1
    1) My guess: to avoid creating unnecessary arrays. 2) I think the null serves as a "terminator". It signifies that "this is the end of the contents of the enum map". – Sweeper Sep 09 '19 at 12:28

2 Answers2

2

It's explained in the javadoc of Set::toArray - basically it's a marker to know where the last element of the set is in the array (assuming the set doesn't contain a null element):

If this set fits in the specified array with room to spare (i.e., the array has more elements than this set), the element in the array immediately following the end of the set is set to null. (This is useful in determining the length of this set only if the caller knows that this set does not contain any null elements.)

assylias
  • 321,522
  • 82
  • 660
  • 783
1

Here you have 2 questions:

What is the purpose of the design EnumMap T[] toArray(T[] a) instead of toArray()?

Same implementation is added for the lists. If you compare T[] toArray(T[] a) with the method toArray(), toArray() returns as Array of Object like Object[], while it is generic implementation for type safety. It tells the method what type of Array need to be created and return rather than creating Object[] always.

Why used var1[var2] = null;

The documentation of this methos says :

If this set fits in the specified array with room to spare (i.e., the array has more elements than this set), the element in the array immediately following the end of the set is set to null. (This is useful in determining the length of this set only if the caller knows that this set does not contain any null elements.)

Gaurav Jeswani
  • 4,410
  • 6
  • 26
  • 47