首先,要明白到下面的一些知识点:
1、collection是hashmap和array的接口
2、hashmap中的元素是没有次序的,而array是有的
3、hashmap转化为array对象时,里面元素的排列顺序与用Iterator遍历原hashmap时的顺序一样。
4、新创建的array对象与参数列表中的列表对象对应起来;collection与原HashMap对应起来(所谓:对应就是某个对象的修改会自动引起另外一个对象的改变)
下面谈谈怎么将一个hashmap对象转化为array对象
首先,将hashmap转化为collection对象
通过:values()方法
为什么可以这么做:
留意到hashmap类,中有一个成员变量:
transient volatile Collection<V> values = null;
再留意hashmap类,中有一个成员函数:
public Collection<V> values() {
Collection<V> vs = values;
return (vs != null ? vs : (values = new Values()));
}
返回的正正是hashmap对象的value值。
说到这里,应该可以留意到你现在手上拿的仅仅是一个collection对象,离我们的目标还有一步之遥。
为了使到一个collection对象变成一个array对象,我们使用以下的方法:
<T> T[] toArray(T[] a);
对于这个方法,我们有必要说明一下。并且举一些例子来验证一下我的理解。
首先,可以看看collection接口的源码中关于<T> T[] toArray(T[] a);的诉述:
(英文还可以的同学建议直接看原版的介绍,因为本人的英语水平有限,可能翻译得不是太理想。怕误人子弟啊!)
/**
* Returns an array containing all of the elements in this collection;
* the runtime type of the returned array is that of the specified array.
* If the collection fits in the specified array, it is returned therein.
* Otherwise, a new array is allocated with the runtime type of the
* specified array and the size of this collection.
*
* <p>If this collection fits in the specified array with room to spare
* (i.e., the array has more elements than this collection), the element
* in the array immediately following the end of the collection is set to
* <tt>null</tt>. (This is useful in determining the length of this
* collection <i>only</i> if the caller knows that this collection does
* not contain any <tt>null</tt> elements.)
*
* <p>If this collection makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the elements in
* the same order.
*
* <p>Like the {@link #toArray()} method, this method acts as bridge between
* array-based and collection-based APIs. Further, this method allows
* precise control over the runtime type of the output array, and may,
* under certain circumstances, be used to save allocation costs.