1.1声明数组,最常用法
int[] intArray1 = {1,2,7,9};//最常使用方法 声明并且赋值
int[] intArray2 = new int[]{1,2,7,9};
int[] intArray3 = new int[4];
1.2数组打印
System.out.println(Arrays.toString(intArray1));//使用Arrays工具类输出数组[1, 2, 7, 9]
System.out.println(intArray1);//直接输出返回的是数组存放的地址 [I@48140564
for (int i = 0; i < intArray1.length; i++) {
System.out.print(intArray1[i]);
}
//输出1279
1.3将数组转化为ArrayList
基本数据类型都采用for each的方式添加
//int类型数组转化为arrayList,foreach将数据一个一个添加进去
ArrayList<Integer> arrayList = new ArrayList<Integer>();
for (int num : intArray1
) {
arrayList.add(num);
}
System.out.println("arrayList的值为" + arrayList);
//string类型数据转为arrayList,直接使用Arrays.asList方法
String[] arrayA = {"a","b","c","d"};
ArrayList<String> arrayList1 = new ArrayList<>(Arrays.asList(arrayA));
为什么int类型的数组不用asList方法?
asList方法的参数是一个可变参数,而基本数据类型是无法作为可变参数传递的,因为它们不是对象
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
1.4将ArrayList转化为数组 toArray()方法
//string类型数据转为arrayList,直接使用Arrays.asList方法
String[] arrayA = {"a","b","c","d"};
ArrayList<String> arrayList1 = new ArrayList<>(Arrays.asList(arrayA));
//ArrayList转为数组,使用toArray方法
String[] arrayB = arrayList1.toArray(new String[arrayList1.size()]);
System.out.println(Arrays.toString(arrayB));//[a, b, c, d]
1.5数组中是否包含某个值
//检查数组中是否包含某个值,使用arraylist中的contains进行判断
System.out.println(arrayList1.contains("a")); //True
//也可以直接写为
System.out.println(Arrays.asList(arrayA).contains("a"));//true
1.6 数组反转
Collections中自带reverse的方法
//反转arrayA
Collections.reverse(Arrays.asList(arrayA));
System.out.println(Arrays.toString(arrayA));//[d, c, b, a]
循环交换元素
public static void reverseArray(int[] array) {
int left = 0;
int right = array.length - 1;
while (left < right) {
int temp = array[left];
array[left] = array[right];
array[right] = temp;
left++;
right--;
}
}
1.7 删除数组中的指定值
class Solution {
public int removeElement(int[] nums, int val) {
int index=0;
for (int i = 0; i < nums.length; i++) {
//数组中的值和目标值不相等的时候,就将该值写入数组中并且index+1
if(nums[i]!=val){
nums[index]=nums[i];
index++;
}
}
return index;
}
}
1.8 复制指定长的数组
//复制数组
String[] arrayC = {"a","b","c","d"};
String[] ArrayD = new String[3];
// public static native void arraycopy(Object src, int srcPos,
// Object dest, int destPos,
// int length);
//src:源数组,即要复制的数组。
//srcPos:源数组中要复制的起始位置。
//dest:目标数组,即复制到的数组。
//destPos:目标数组中复制的起始位置。
//length:要复制的元素个数。
System.arraycopy(arrayC, 0, ArrayD, 0, 3);
System.out.println(Arrays.toString(ArrayD));//[a, b, c]