A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 江月念华 中级黑马   /  2016-9-22 23:33  /  509 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

发现集合和数组要经常互换,有没有简单的方法进行转换

5 个回复

倒序浏览
CreScert 来自手机 中级黑马 2016-9-22 23:38:05
沙发
to....不是有方法了吗?去jdk查查哇哇哇
回复 使用道具 举报
集合转数组:  list.toArray(); // 返回一个数组     数组转集合:  遍历数组添加到集合中
回复 使用道具 举报
集合转化为数组,用toArray()的情况不多,因为转化后为引用数据类型,基本很少。一般都需要遍历后一个一个添加。到是字符串和数组之间转换的比较多
回复 使用道具 举报
ArrayList的源码
[Java] 纯文本查看 复制代码
 /**
     * Returns an array containing all of the elements in this list
     * in proper sequence (from first to last element).
     *
     * <p>The returned array will be "safe" in that no references to it are
     * maintained by this list.  (In other words, this method must allocate
     * a new array).  The caller is thus free to modify the returned array.
     *
     * <p>This method acts as bridge between array-based and collection-based
     * APIs.
     *
     * @return an array containing all of the elements in this list in
     *         proper sequence
     */
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    /**
     * Returns an array containing all of the elements in this list in proper
     * sequence (from first to last element); the runtime type of the returned
     * array is that of the specified array.  If the list 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 list.
     *
     * <p>If the list fits in the specified array with room to spare
     * (i.e., the array has more elements than the list), 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 the
     * list <i>only</i> if the caller knows that the list does not contain
     * any null elements.)
     *
     * @param a the array into which the elements of the list are to
     *          be stored, if it is big enough; otherwise, a new array of the
     *          same runtime type is allocated for this purpose.
     * @return an array containing the elements of the list
     * @throws ArrayStoreException if the runtime type of the specified array
     *         is not a supertype of the runtime type of every element in
     *         this list
     * @throws NullPointerException if the specified array is null
     */
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }
回复 使用道具 举报
Hblack 来自手机 初级黑马 2016-9-23 12:32:13
地板
数组转集合aslist,集合转数组toArray


注意数组直接转集合后,集合长度不能增减
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马