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?
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.)