初始化数组的方式
package Arrays;
import java.util.*;
class Person{}
public class ArrayOptions {
public static void main(String[] args) {
/**
* 对象数组
*/
Person[] p1;//没有初始化的局部变量,在没有初始化之前不允许使用。
//1、
Person[] p2=new Person[2];//对象数组中是null
System.out.println("p2:"+Arrays.toString(p2)); //p2:[null, null]
//2、
Person[] p3=new Person[2];
for(int i=0;i<p3.length;i++){
p3[i]=new Person();//通过循环给数组中放对象
}
//3、
Person[] p4={new Person(),new Person(),new Person()};
//4、前面声明,后面初始化。
p1=new Person[]{new Person(),new Person()};
System.out.println("P1:"+Arrays.toString(p1));//P1:[Arrays.Person@15db9742, Arrays.Person@6d06d69c]
/**
* 基本类型数组
*/
int[] a;
int[] b=new int[2];
System.out.println("b:"+Arrays.toString(b));//b:[0, 0]
int[] c=new int[2];
for(int i=0;i<c.length;i++){
c[i]=i;
}
System.out.println("c:"+Arrays.toString(c));//c:[0, 1]
int[] d={2,3,1};
System.out.println("d:"+Arrays.toString(d));//d:[2, 3, 1]
a=new int[]{3,5,6};
System.out.println("a:"+Arrays.toString(a));//a:[3, 5, 6]
char[] f=new char[2];
System.out.println("f:"+Arrays.toString(f));
System.out.println(Arrays.toString(returnArray()));//[joaid, ajoid]
}
/**
* 返回一个数组
* @return
*/
public static String[] returnArray(){
String[] c=new String[]{"joaid","ajoid"};
return c;
}
}
对象数组中保存的是对象的引用,基本类型数组中保存值。
对象数组和基本类型数组的使用基本相同
复制数组
1、System.arraycopy(源数组,从源数组的什么位置开始复制,目标数组,从目标数组什么位置开始复制,需要复制的元素个数)
//基本类型
int[] g=new int[]{1,2,3};
int[] h=new int[]{4,5,6,8,9};
System.arraycopy(g,0,h,0,g.length);
System.out.println("g:"+Arrays.toString(g));//g:[1, 2, 3]
System.out.println("h:"+Arrays.toString(h));//h:[1, 2, 3, 8, 9]
g[1]=5;//更改
System.out.println("g:"+Arrays.toString(g));//g:[1, 5, 3]
System.out.println("h:"+Arrays.toString(h));//h:[1, 2, 3, 8, 9]
//引用类型(两者指向一个地址,一个变都变)
Person[] p5=new Person[]{new Person(),new Person(),new Person()};
Person[] p6=new Person[5];
System.arraycopy(p5,0,p6,0,p5.length);
System.out.println("p5"+Arrays.toString(p5));//p5[id=2, id=2, id=2]
System.out.println("p6"+Arrays.toString(p6));//p6[id=2, id=2, id=2, null, null]
p5[1].setId(5);
System.out.println("p5"+Arrays.toString(p5));//p5[id=2, id=5, id=2]
System.out.println("p6"+Arrays.toString(p6));//p6[id=2, id=5, id=2, null, null]
2、clone()
int[] i=new int[]{1,2,3,2,1};
int[] j=i.clone();
i[1]=5;//更改
System.out.println("i"+Arrays.toString(i));//i[1, 5, 3, 2, 1]
System.out.println("j"+Arrays.toString(j));//j[1, 2, 3, 2, 1] 不随着改变
3、Arrays.copyOf(原始数组, 新数组长度);
int[] k=new int[]{2,5,3,6,9};
int[] l;
l=Arrays.copyOf(k,k.length);
System.out.println("l:"+Arrays.toString(l));//l:[2, 5, 3, 6, 9]
k[2]=5;
System.out.println("k:"+Arrays.toString(k));//k:[2, 5, 5, 6, 9]
System.out.println("l:"+Arrays.toString(l));//l:[2, 5, 3, 6, 9]
在上面3中复制数组中,在对象数组中,都是浅复制,复制后的数组和源数组指向同一片地址,只是复制了对象的引用,而不是对象本身的拷贝。
删除排序数组中的重复项
如:nums = [0,0,1,1,1,2,2,3,3,4],
因为是已经排好序的数组,可以用双指针法,比较前后两个数字即可
public int removeDuplicates(int[] nums) {
//双指针:比较前一个与现有数字是否相等。
int j=1;//用来记录不同的数字,2、最后返回。
for(int i=1;i<nums.length;i++){
if(nums[i]!=nums[i-1]){
nums[j]=nums[i];
j++;
}
}
return j;
}