码迷,mamicode.com
首页 > 编程语言 > 详细

java变参

时间:2015-09-22 12:47:36      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

java变参是通过数组来实现的

Object[] addAll(Object[] array1, Object... array2)和Object[] addAll(Object[] array1, Object[] array2)签名应该一致的。
public class ArrayUtils {
    // Clone
    // -----------------------------------------------------------------------
    /**
     * <p>
     * Shallow clones an array returning a typecast result and handling <code>null</code>.
     * </p>
     * 
     * <p>
     * The objects in the array are not cloned, thus there is no special handling for multi-dimensional arrays.
     * </p>
     * 
     * <p>
     * This method returns <code>null</code> for a <code>null</code> input array.
     * </p>
     * 
     * @param array
     *            the array to shallow clone, may be <code>null</code>
     * @return the cloned array, <code>null</code> if <code>null</code> input
     */
    public static Object[] clone(Object[] array) {
        if (array == null) {
            return null;
        }
        return array.clone();
    }

/**
     * <p>
     * Adds all the elements of the given arrays into a new array.
     * </p>
     * <p>
     * The new array contains all of the element of <code>array1</code> followed by all of the elements <code>array2</code>.
     * When an array is returned, it is always a new array.
     * </p>
     * 
     * <pre>
     * ArrayUtils.addAll(null, null)     = null
     * ArrayUtils.addAll(array1, null)   = cloned copy of array1
     * ArrayUtils.addAll(null, array2)   = cloned copy of array2
     * ArrayUtils.addAll([], [])         = []
     * ArrayUtils.addAll([null], [null]) = [null, null]
     * ArrayUtils.addAll(["a", "b", "c"], ["1", "2", "3"]) = ["a", "b", "c", "1", "2", "3"]
     * </pre>
     * 
     * @param array1
     *            the first array whose elements are added to the new array, may be <code>null</code>
     * @param array2
     *            the second array whose elements are added to the new array, may be <code>null</code>
     * @return The new array, <code>null</code> if <code>null</code> array inputs. The type of the new array is the type of the
     *         first array.
     * @since 2.1
     */
    public static Object[] addAll(Object[] array1, Object... array2) {
        if (array1 == null) {
            return clone(array2);
        } else if (array2 == null) {
            return clone(array1);
        }
        Object[] joinedArray = (Object[]) Array
                .newInstance(array1.getClass().getComponentType(), array1.length + array2.length);
        System.arraycopy(array1, 0, joinedArray, 0, array1.length);
        System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
        return joinedArray;
    }
    /**
     * Swaps the two specified elements in the specified array.
     * 
     * @param arr
     * @param i
     * @param j
     */

    public static void swap(Object[] arr, int i, int j) {
        Object tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}

测试变参

 public static void main(String[] args) {
        String[] array = { "22", "66" };
        // The argument of type String[] should explicitly be cast to Object[] for the invocation of the varargs method
        // addAll(Object[], Object...) from type ArrayUtils. It could alternatively be cast to Object for a varargs invocation
        System.out.println(Arrays.toString(ArrayUtils.addAll(array, new String[] { "2", "6" }))); // Compile warning
        System.out.println(Arrays.toString(ArrayUtils.addAll(array, "2", "6"))); // OK
        System.out.println(Arrays.toString(ArrayUtils.addAll(array, (Object[]) new String[] { "2", "6" }))); // OK
        System.out.println(Arrays.toString(ArrayUtils.addAll(array, (Object) new String[] { "2", "6" })));// java.lang.ArrayStoreException
    }

 自动包装

Object[] addAll(Object[] array1, Object... array2)
--> 传参:Object[] addAll(Object[] array1, Object array2_0, Object array2_1, Object array2_2, ...)
--> 变长参数包装:Object[] array2 = new Object[]{array2_0, array2_1, array2_2};
--> 编译后实际的:Object[] addAll(Object[] array1, Object[] array2)

由于实际函数是Object[] addAll(Object[] array1, Object[] array2),则在变长参数位置直接传递数组时,编译器给出警告。

  • 默认的数组直接作为实际函数Object[] addAll(Object[] array1, Object[] array2)的第二参数,
  • 消除警告可以添加强制转换,规定是(Object[])和默认方式相同;(Object)则作为变长参数的一项,自动包装为new Object[]{(Object) new String[] { "2", "6" }},变成了二维数组,String型数组不能存储元素String[]的对象(String[] joinedArray; joinedArray[0] = new String[] { "2", "6" }是不正确的),则在第二个System.arraycopy发生存储异常

 另外的消除编译警告还可以这样,通过泛型

    public static <T> Object[] addAll(Object[] array1, T... array2) {
        if (array1 == null) {
            return clone(array2);
        } else if (array2 == null) {
            return clone(array1);
        }
        Object[] joinedArray = (Object[]) Array
                .newInstance(array1.getClass().getComponentType(), array1.length + array2.length);
        System.arraycopy(array1, 0, joinedArray, 0, array1.length);
        System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
        return joinedArray;
    }

 

缺点是编译时如果array2类型不是全部一样,会被检查,如

String[] array = { "22", "66" };

System.out.println(Arrays.toString(ArrayUtils.addAll(array, new Object[] { "2", "6", 2 }))); 
System.out.println(Arrays.toString(ArrayUtils.addAll(array, "2", "6", 2))); 

继续执行,只会得到java.lang.ArrayStoreException。除非第一参数是Object[] array = { "22", "66" };才能即能存储String又能存储Integer(上面的2)

 

java变参

标签:

原文地址:http://www.cnblogs.com/Fang3s/p/4828390.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!