面试初级Java开发问到Arrays
作者:蛋挞学姐 发布时间:2023-11-27 05:40:04
一、基本定义
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);//加入Java开发交流君样:593142328一起吹水聊天
List<int[]> list3 = Arrays.asList(array2);
2.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//加入Java开发交流君样:593142328一起吹水聊天
* @param val the value to be stored in all elements of the array
* @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>
* @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or
* <tt>toIndex > a.length</tt> */
public static void fill(double[] a, int fromIndex, int toIndex,double val){
rangeCheck(a.length, fromIndex, toIndex); for (
int i = fromIndex; i < toIndex; i++)
a[i] = val;
} /** * Assigns the specified float value to each element of the specified array
* of floats.
*
* @param a the array to be filled
* @param val the value to be stored in all elements of the array */
public static void fill(float[] a, float val) {
for (int i = 0, len = a.length; i < len; i++)
a[i] = val;
} /** * Checks that {@code fromIndex} and {@code toIndex} are in
* the range and throws an exception if they aren't. */
private static void rangeCheck(int arrayLength, int fromIndex, int toIndex) {
if (fromIndex > toIndex) { throw new IllegalArgumentException( "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
} if (fromIndex < 0) {
throw new ArrayIndexOutOfBoundsException(fromIndex);
} if (toIndex > arrayLength) {//加入Java开发交流君样:593142328一起吹水聊天
throw new ArrayIndexOutOfBoundsException(toIndex);
}
}
3.int[] copyOf(int[] original, int newLength)、int[] copyOfRange(int[] original, int from, int to)
存在多个重载方式,此处以int举例
从样例中我i们看到,copyOf复制后的数组长度可以大于复制前的数组,根据源码发现,超出的元素被填充为0,引用类型则填充为null
int[] array = new int[]{1,2,3};
int[] array2 = Arrays.copyOf(array, 4);
public static int[] copyOf(
int[] original, int newLength) {
int[] copy = new int[newLength];
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
对于copyOfRange,可以选择复制的开头和结尾(不包括),且结尾下标可以大于原数组长度,超出的下标会被填充
int[] array = new int[]{1,2,3,4,5,6,7,8,9};
int[] array2 = Arrays.copyOfRange(array, 3, 6);
int[] array3 = Arrays.copyOfRange(array, 3, 10);
/** * Copies the specified range of the specified array into a new array.
* The initial index of the range (<tt>from</tt>) must lie between zero
* and <tt>original.length</tt>, inclusive. The value at
* <tt>original[from]</tt> is placed into the initial element of the copy
* (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
* Values from subsequent elements in the original array are placed into
* subsequent elements in the copy. The final index of the range
* (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
* may be greater than <tt>original.length</tt>, in which case
* <tt>0</tt> is placed in all elements of the copy whose index is
* greater than or equal to <tt>original.length - from</tt>. The length
* of the returned array will be <tt>to - from</tt>.
*
* @param original the array from which a range is to be copied
* @param from the initial index of the range to be copied, inclusive
* @param to the final index of the range to be copied, exclusive.
* (This index may lie outside the array.)
* @return a new array containing the specified range from the original array,
* truncated or padded with zeros to obtain the required length
* @throws ArrayIndexOutOfBoundsException if {@code from < 0}
* or {@code from > original.length}
* @throws IllegalArgumentException if <tt>from > to</tt>
* @throws NullPointerException if <tt>original</tt> is null
* @since 1.6 *///加入Java开发交流君样:593142328一起吹水聊天
public static int[] copyOfRange(int[] original, int from, int to) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); int[] copy = new int[newLength];
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength)); return copy;
}
4.boolean equals(int[] a, int[] a2)、boolean equals(Object[] a, Object[] a2)
比较2个数组是否相等,基本类型的元素会依次进行==判断,引用类型则会在判空后使用equals【白嫖资料】
public static boolean equals(int[] a, int[] a2) { if (a==a2) return true; if (a==null || a2==null) return false; int length = a.length; if (a2.length != length) return false; for (int i=0; i<length; i++) if (a[i] != a2[i]) return false; return true;
} public static boolean equals(Object[] a, Object[] a2) { if (a==a2) return true; if (a==null || a2==null) return false; int length = a.length; if (a2.length != length) return false; for (int i=0; i<length; i++) {
Object o1 = a[i];
Object o2 = a2[i]; if (!(o1==null ? o2==null : o1.equals(o2))) return false;
} return true;
}
5.String toString(int[] a)
假设我们想输出一个数组的全部元素,一种方法是利用循环遍历所有元素后挨个输出
但Arrays提供了一个方案可以直接调用,toString内部实现其实也是通过遍历来实现,
利用可变字符串StringBuilder来构建
public static String toString(int[] a) {
if (a == null) return "null"; int iMax = a.length - 1; if (iMax == -1) return "[]";
StringBuilder b = new StringBuilder();
b.append('['); for (int i = 0; ; i++) {
b.append(a[i]); if (i == iMax) return b.append(']').toString();
b.append(", ");
}
}
6.int binarySearch(int[] a, int key)
Arrays内置的二分查找方法,使用条件为参数数组a是有序的,如无序
会导致返回结果错误
1 public static int binarySearch(int[] a, int fromIndex, int toIndex,
2 int key) {
3 rangeCheck(a.length, fromIndex, toIndex);
4 return binarySearch0(a, fromIndex, toIndex, key);
5 }
6
7 // Like public version, but without range checks.
8 private static int binarySearch0(int[] a, int fromIndex, int toIndex,
9 int key) {
10 int low = fromIndex;
11 int high = toIndex - 1;
12
13 while (low <= high) {
14 int mid = (low + high) >>> 1;
15 int midVal = a[mid];
16
17 if (midVal < key)
18 low = mid + 1;
19 else if (midVal > key)
20 high = mid - 1;
21 else
22 return mid; // key found
23 }
24 return -(low + 1); // key not found.
25 }
来源:https://blog.csdn.net/wj1314250/article/details/118615724


猜你喜欢
- 在 Windows 窗体应用程序中显示图片时要使用图片控件 ( PictureBox ),图片的设置方式与背景图片的设置方式相似。图片控件中
- 下载:1.在spring-mvc中配置(用于100M以下的文件下载)<bean class="org.springframe
- Dart实体类格式class CategoryMo { String name; int count;CategoryMo({this.na
- PictureBox 控件可以显示来自位图、图标或者元文件,以及来自增强的元文件、JPEG 或 GIF 文件的图形。如果控件不足以显示整幅图
- XML:Extensible Markup Language(可扩展标记语言)的缩写,是用来定义其它语言的一种元语言,其前身是SGML(St
- //======================================//输出格式: hex2bin 5e.//得到: 0101
- 本文实例为大家分享了java实现饮料自助售货机的具体代码,供大家参考,具体内容如下①用户类import java.util.Scanner;
- 引言mysql 和 oracle 插入的时候有一个很大的区别是:oracle 支持序列做 id;mysql 本身有一个列可以做自增长字段。m
- 在实际的应用程序开发中,我们有时需要把 Activity 设置成全屏显示,一般情况下,可以通过两种方式来设置全屏显示效果:其一,通过在代码中
- 前言 这其实是一道面试题,是我在面试百度的时候被问到的,当时没有答出来(因为自己真的很菜),后来在网上寻找答案,看到也是一头雾水,
- 一、Surface 概述OpenGL ES/Skia定义了一组绘制接口的规范,为什么能够跨平台? 本质上需要与对应平台上的本地窗口建立连接。
- GoogleNow是Android4.1全新推出的一款应用他,它可以全面了解你的使用习惯,并为你提供现在或者未来可能用到的各种信息,Goog
- Swing包的介绍Java基础类数据库(Java Foundation Class)给java应用程序增加了图形界面、丰富的功能性以及与用户
- 上一篇 主要介绍了如何通过蓝牙连接到打印机。这一篇,我们就介绍如何向打印机发送打印指令,来打印字符和图片。1. 构造输出流首先要明确一点,就
- 需求背景最近的一个项目,在项目基本完工的阶段,客户提出要将所有业务操作的日志记录到数据库中,并且要提取一些业务的关键信息(比如交易单号)体现
- Android系统支持的颜色是由4个值组成的,前3个为RGB,也就是我们常说的三原色(红、绿、蓝),最后一个值是A,也就是Alpha。这4个
- MyBatis 的一个强大的特性之一通常是它的动态 SQL 能力。如果你有使用 JDBC 或其他 相似框架的经验,你就明白条件地串联 SQL
- 推荐第三种方式,简单快捷不卡。第一种:jjdxm_updateGitHub地址:jjdxmashl/jjdxm_update效果图:点击立即
- 一: Environment.StackTrace可能我们看到最多的就是catch中的e参数,里面会有一个StackTrace,然后不可否认
- 在文本框中输入一个数字,点击开始累加按钮,程序计算从1开始累计到该数字的结果。因为该累加过程比较耗时,如果直接在UI线程中进行,那么当前窗口