Arrays用法整理

本文将整理  java.util.Arrays  工具类比较常用的方法: 
本文介绍的方法基于JDK 1.7 之上。 
1.  asList方法   
@SafeVarargs
    public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }
   使用该方法可以返回一个固定大小的List,如: 
List<String> stringList = Arrays.asList("Welcome", "To", "Java",
        "World!");

    List<Integer> intList = Arrays.asList(1, 2, 3, 4);
   
2. binarySearch方法  

binarySearch方法支持在整个数组中查找,如: 
int index = Arrays.binarySearch(new int[] { 1, 2, 3, 4, 5, 6, 7 }, 6);
以及在某个区间范围内查找, 如: 
public static int binarySearch(int[] a, int fromIndex, int toIndex,
                                   int key) {
        rangeCheck(a.length, fromIndex, toIndex);
        return binarySearch0(a, fromIndex, toIndex, key);
    }
int index = Arrays.binarySearch(new int[] { 1, 2, 3, 4, 5, 6, 7 }, 1, 6, 6);
3. copyOf及copyOfRange方法  

如: 
String[] names2 = { "Eric", "John", "Alan", "Liz" };


    //[Eric, John, Alan]
    String[] copy = Arrays.copyOf(names2, 3);
    
    //[Alan, Liz]
    String[] rangeCopy = Arrays.copyOfRange(names2, 2,
        names2.length);
4. sort方法  
String[] names = { "Liz", "John", "Eric", "Alan" };
//只排序前两个
//[John, Liz, Eric, Alan]
Arrays.sort(names, 0, 2);
//全部排序
//[Alan, Eric, John, Liz]
Arrays.sort(names);
另外,Arrays的sort方法也可以结合比较器,完成更加复杂的排序。 
public static <T> void sort(T[] a, Comparator<? super T> c) {
        if (LegacyMergeSort.userRequested)
            legacyMergeSort(a, c);
        else
            TimSort.sort(a, c);
    }
5. toString方法  
Arrays的toString方法可以方便我们打印出数组内容。 
如: 
String[] names = { "Liz", "John", "Eric", "Alan" };
  Arrays.sort(names);
  System.out.println(Arrays.toString(names));
控制台将打印出  [Alan, Eric, John, Liz]  
6. deepToString方法  
如果需要打印二维数组的内容: 
int[][] stuGrades = { { 80, 81, 82 }, { 84, 85, 86 }, { 87, 88, 89 } }; 
如果直接用
System.out.println(Arrays.toString(stuGrades));
那么得到的结果类似于 
     [[I@35ce36, [I@757aef, [I@d9f9c3]} 
这个时候得用  deepToString  方法才能得到正确的结果[[80, 81, 82], [84, 85, 86], [87, 88, 89]] 
System.out.println(Arrays.deepToString(stuGrades));
7. equals方法  
使用Arrays.equals来比较1维数组是否相等。 
String[] names1 = { "Eric", "John", "Alan", "Liz" };

    String[] names2 = { "Eric", "John", "Alan", "Liz" };

    System.out.println(Arrays.equals(names1, names2));
8. deepEquals方法  
Arrays.deepEquals能够去判断更加复杂的数组是否相等。 
int[][] stuGrades1 = { { 80, 81, 82 }, { 84, 85, 86 }, { 87, 88, 89 } };

    int[][] stuGrades2 = { { 80, 81, 82 }, { 84, 85, 86 }, { 87, 88, 89 } };

    System.out.println(Arrays.deepEquals(stuGrades1, stuGrades2));
9. fill方法  
int[] array1 = new int[8];
    Arrays.fill(array1, 1);
    //[1, 1, 1, 1, 1, 1, 1, 1]
    System.out.println(array1.toString())
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值