java_colletction应用:从hashmap到array的转换

 首先,要明白到下面的一些知识点:

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.
    

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值