世道变了,面试初级Java开发会问到Arrays!!!你不会还不知道吧!

一、基本定义

Arrays类,全路径java.util.Arrays,主要功能为操作数组,Arrays类的所有方法均为静态方法,所以

调用方式全部为Arrays.方法名

二、常用方法

1. <T> List<T>  asList(T... a)

可以将数组转化为相应的list集合,但是也只能转化为list,asList方法内部构建了一个内部静态类ArrayList

这个ArrayList也继承自AbstractList,但并不是我们集合中常用的ArrayList,这两者是有区别的,需注意,

内部静态类AbstractList也实现了contains,forEach,replaceAll,sort,toArray等方法,但add,remove等方法则没有

Integer[] array = new Integer[]{
   1,2,3}; 
int[] array2 = new int[]{
   1,2,3};
List<Integer> list1 = Arrays.asList(1,2,3);
List<Integer> list2 = Arrays.asList(array);
List<int[]> list3 = Arrays.asList(array2);
  1. void fill(int[] a, int val)、void fill(int[] a, int fromIndex, int toIndex, int val)、void fill(Object[] a, Object val)、void fill(Object[] a, int fromIndex, int toIndex, Object val)

fill方法有多个重载,分别对应几种基本数据类型以及引用类型(Object),

fill(int[] a, int val)会将整个数组的值全部覆盖为val
fill(int[] a, int fromIndex, int toIndex, int val)则提供了可选的开头和结尾(不包括)

int[] array = new int[]{
   1,2,3};
Arrays.fill(array, 1);
Arrays.fill(array, 0, 2, 1);// {1,1,3}
String[] str = {
   "123"};
Arrays.fill(str, "1");

源码如下:

我们可以看到可选开头结尾的重载方法会先做数组越界的校验,防止非法输入

   /** * Assigns the specified double value to each element of the specified
     * range of the specified array of doubles.  The range to be filled
     * extends from index <tt>fromIndex</tt>, inclusive, to index
     * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
     * range to be filled is empty.)
     *
     * @param a the array to be filled
     * @param fromIndex the index of the first element (inclusive) to be
     *        filled with the specified value
     * @param toIndex the index of the last element (exclusive) to be
     *        filled with the specified value
     * @param val the value to be stored in all elements of the array
     * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
     * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
     *         <tt>toIndex &gt; a.length</tt> */
    public static void fill(double
  • 12
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java架构没有996

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值