Java中集合的toArray方法使用

1、参考博文:https://blog.csdn.net/enjoy96/article/details/78628328

2、在Collection集合中,将集合转为数组有两个方法

(1)按适当顺序(从第一个元素到最后一个元素)返回包含此列表所有元素的数组。

   /**
     * 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 even if this list is backed by an 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
     * @see Arrays#asList(Object[])
     */
    Object[] toArray();

(2)按适当顺序(从第一个元素到最后一个元素)返回包含此列表所有元素的数组。返回数组的类型是运行时指定数组的类型。

    /**
     * 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 list 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.)
     *
     * <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.
     *
     * <p>Suppose <tt>x</tt> is a list known to contain only strings.
     * The following code can be used to dump the list into a newly
     * allocated array of <tt>String</tt>:
     *
     * <pre>{@code
     *     String[] y = x.toArray(new String[0]);
     * }</pre>
     *
     * Note that <tt>toArray(new Object[0])</tt> is identical in function to
     * <tt>toArray()</tt>.
     *
     * @param a the array into which the elements of this 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 this 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
     */
    <T> T[] toArray(T[] a);

3、两种方法的使用

(1)Object[] toArray();

    public static void main(String[] args) {
        List<Integer> myList = new ArrayList<>();
        myList.add(500);
        myList.add(20);
        myList.add(0);

        Object[] obj = myList.toArray();
        for (int i = 0; i < obj.length; i++) {
            Integer num = (Integer) obj[i];
            System.out.println(num);
        }

//        Integer[] obj = (Integer[])myList.toArray();
//        for (int i = 0; i < obj.length; i++) {
//            System.out.println(obj[i]);
//        }
        //报错:Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
        //	at com.test.facade.SortTest.main
    }

打印:

(2)<T> T[] toArray(T[] a);

    public static void main(String[] args) {
        List<Integer> myList = new ArrayList<>();
        myList.add(500);
        myList.add(20);
        myList.add(0);

        Integer[] nums = myList.toArray(new Integer[myList.size()]);
        for (int i = 0; i < nums.length; i++) {
            System.out.println(nums[i]);
        }
    }

打印:

4、算法练习

(1)题目描述

(2)代码实现

    /**
     * 滑动窗口进行求解
     * 滑动窗口:窗口范围:[i,j)   边界中i和j都只能向前
     * 假设  1+2+3+...+10<taget
     *      1+2+3+...+10+11>taget => 说明1开头的序列找不到
     *      
     *      ...开始找2开头的序列...
     *      
     *      又2+3+...+10 < 1+2+3+...+10 < taget
     *      所以2开头的序列 2+3+...+10 一定会加11,即判断2+3+...+10+11与target的大小
     * 综上:滑动窗口一定可以计算出所有符合条件的解。
     */
    private int[][] findContinuousSequence(int target) {
        int i = 1;//滑动窗口左边界
        int j = 1;//滑动窗口右边界
        int sum = 0;//滑动窗口中数据之和
        List<int[]> res = new ArrayList<>();
        while (i <= target / 2) {
            if (sum < target) {
                //右边界向右扩大
                sum += j;
                j++;
            } else if (sum > target) {
                //左边界向右,缩小整个滑动窗口
                sum -= i;
                i++;
            } else {
                //收集结果
                int[] arr = new int[j - i];
                for (int k = i; k < j; k++) {
                    arr[k - i] = k;//结果集从0开始记录
                }
                res.add(arr);
                sum -= i;
                i++;
            }
        }
        return res.toArray(new int[res.size()][]);//匿名数组对象
    }

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值