英文:
How do I add to the first empty index in a generic type array?
问题
我正在从头开始使用通用类型(generic types)创建一个ArrayList类,其中我需要包含一个将元素添加到第一个空索引的方法。
我使用T[] list = (T[]) new Comparable[size];
来初始化数组。
假设 size = 10;
并且索引0-3已填充了各种对象。我该如何找到索引4作为第一个空索引?通用类型的数组是用null还是其他方式初始化的?
谢谢。
英文:
I am making an ArrayList class from scratch using generic types, and one of the methods I need to include is one that adds an element to the first empty index in the arrayList.
I initialized the array with T[] list = (T[]) new Comparable[size];
Say size = 10;
and indices 0-3 are filled with various Objects. How would I locate index 4 as the first empty index? Are generic arrays initialized with nulls or something else?
Thank you
答案1
得分: 0
在Java中,实际上有两种类型的数组:原始数组和对象数组。提示:泛型是对象。
原始数组的元素被初始化为0
,或者对于boolean[]
来说是false
,而对象数组的元素则被初始化为null
。
这些都是相同的默认值,也会赋予给给定类型的字段,例如,像这样的字段默认情况下将是null
:
private Comparable<Foo> comparable;
英文:
There are really 2 types of arrays in Java: Primitive arrays and object arrays. Hint: Generics are objects.
The elements of primitive arrays are initialized to 0
, or false
for a boolean[]
, and the elements of object arrays are initialized to null
.
Those are the exact same default values that are also assigned to fields of the given types, e.g. a field like this will be null
by default:
private Comparable<Foo> comparable;
专注分享java语言的经验与见解,让所有开发者获益!
评论