要点Java19 java.util.Arrays

Arrays 数组帮助类

示例程序(JUnit演示)

数组转化为List

    @Test
    public void testUserArraysChangeArraytoList() {
        // 类Arrays
        // public static <T> List<T> asList(T... a) 
        // Returns a fixed-size list backed by the specified array

        List<Integer> testList = Arrays.asList(1, 2, 3);
        assertEquals("生成大小为3的List", 3, testList.size());

        List<Integer> testList1 = Arrays.asList(1, 2);
        assertEquals("生成大小为2的List", 2, testList1.size());
    }

    @Test(expected = UnsupportedOperationException.class)
    public void isFixedList() {
        // 类Arrays
        // public static <T> List<T> asList(T... a) 
        // Returns a fixed-size list backed by the specified array
        Integer[] test = {1,2,3};
        List<Integer> testList = Arrays.asList(test);
        assertEquals("生成大小为3的List", 3, testList.size());
        testList.add(4);//throw UnsupportedOperationException
    }

排序

    @Test
    public void testSort() {
        // 类Arrays
        // void java.util.Arrays.sort(Object[] a)
        // 排序
        Integer[] test = {3,2,1};
        Arrays.sort(test);
        assertEquals( 1, test[0].intValue() );

    }

其他方法

    @Test
    public void testEquals() {  
        Integer[] test1 = {3,2,1};
        Integer[] test2 = {3,2,1};  
        Integer[] test3 = {1,2,3};  

        //equals
        assertTrue(Arrays.equals(test1, test2));
        assertFalse(Arrays.equals(test1, test3));

        //toString
        assertEquals( "[3, 2, 1]", Arrays.toString(test1) );

        //copyOf
        assertEquals( "[3, 2]", Arrays.toString(Arrays.copyOf(test1, 2)) );

        //fill
        Arrays.fill(test1, 2);
        assertEquals( "[2, 2, 2]", Arrays.toString(test1) );
    }

环境 jdk1.6 window7 junit4

要点Java19 java.util.Arrays,布布扣,bubuko.com

要点Java19 java.util.Arrays

上一篇:Java几种常用的实现排序方法


下一篇:0521.使用UIWebView加载来自NetWork、Project、Documents的html、javascript文件