gpt4 book ai didi

java - EnumMap T[] toArray(T[] a) 实现

转载 作者:行者123 更新时间:2023-11-29 04:07:16 24 4
gpt4 key购买 nike

我发现 EnumMap T[] toArray(T[] var2) 有这样的实现:

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);
}

我不明白什么是真正的意思:

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

如果我们的数组例如 String[5] 并且我们尝试:

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);
}

输出是:

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

1)设计EnumMap T[] toArray(T[] a)而不是toArray()的目的是什么?

2)为什么用

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

是否为迭代器标记N+1元素为null?

最佳答案

the javadoc of Set::toArray 中有解释- 基本上它是一个标记,用于知道集合的最后一个元素在数组中的位置(假设集合不包含 null 元素):

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

关于java - EnumMap T[] toArray(T[] a) 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57853998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com