1.二维数组:
public class TwoArray {
public static void main(String[] args) {
//看下面的内存分析图便于理解
/* int [][] a = {
{1,2},
{3,4,0,9},
{5,6,7}
};*/
int[][] a = new int[3][];
a[0] = new int[2];
a[1] = new int[4];
a[2] = new int[3];
a[0][0] = 1;
a[0][1] = 2;
a[1][0] = 3;
a[1][1] = 4;
a[1][2] = 0;
a[1][3] = 9;
a[2][0] = 5;
a[2][1] = 6;
a[2][2] = 7;
System.out.println(a[0][0]);//1
}
}
2.数组的常见操作
.数组的拷贝
System类里也包含了一个static void arraycopy(object src,int srcpos,object dest, int destpos,int length)方法,该方法可以将src数组里的元素值赋给dest数组的元素,其中srcpos指定从src数组的第几个元素开始赋值,length参数指定将src数组的多少个元素赋给dest数组的元素。
String[] s = {"Mircosoft","IBM","Sun","Oracle","Apple"};
String[] sBak = new String[6];
System.arraycopy(s,0,sBak,0,s.length);
.数组排序
①基本数据类型:自动排
int[] a = {1,2,323,23,543,12,59};
System.out.println(Arrays.toString(a));
Arrays.sort(a);
System.out.println(Arrays.toString(a));
结果:
[1, 2, 323, 23, 543, 12, 59]
[1, 2, 12, 23, 59, 323, 543]
②如果数组元素是引用类型,那么需要怎么做呢?
需要实现compareTo接口:
public class Test{
public static void main(String[] args) {
Man[] msMans = {new Man(3,"a"),new Man(60,"b"),new Man(2,"c")};
Arrays.sort(msMans);
System.out.println(Arrays.toString(msMans));
}
}
class Man implements Comparable {
int age;
int id;
String name;
public Man(int age, String name) {
super();
this.age = age;
this.name = name;
}
public String toString(){
return this.name;
}
//实现这个接口
如果指定的数与参数相等返回0。
如果指定的数小于参数返回 -1。
如果指定的数大于参数返回 1
public int compareTo(Object o) {
Man man = (Man) o;
if(this.age<man.age){
return -1;
}
if(this.age>man.age){
return 1;
}
return 0;
}
.二分法查找
int[] a = {1,2,323,23,543,12,59};
Arrays.sort(a); //使用二分法查找,必须先对数组进行排序
System.out.println("该元素的索引:"+Arrays.binarySearch(a, 12));//2
.asList
int[] a = {1,2,323,23,543,12,59};
List<int[]> list = new ArrayList<int[]>();
list = Arrays.asList(a); //将数组转成成list对象中的一个元素
System.out.println(list.get(0)[1]);