1.数组声明
例如:int[] s = new int[];
2.数组初始化
1.静态初始化
int[] a = { 1, 2, 3 };
2.动态初始化
int[] a1 = new int[2]; a1[0]=1;
3.数组的默认初始化
int a2[] = new int[2]; // 默认值:0,0
boolean[] b = new boolean[2]; // 默认值:false,false
String[] s = new String[2]; // 默认值:null, null
4.数组的遍历
增强for循环:
String[] ss = { "aa", "bbb", "ccc", "ddd" };
for (String temp : ss) {
System.out.println(temp);}
5.数组的拷贝
arraycopy(object src,int srcpos,object dest, int destpos,int length)。其中srcpos指定从src数组的第几个元素开始赋值,length参数指定将src数组的多少个元素赋给dest数组的元素。
6.常用数组方法
打印:Arrays.toString(a)
排序:Arrays.sort(a);
数组元素是引用类型的排序(Comparable接口的应用):类继承compara接口
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;
}
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;
}
}
二分法查找:Arrays.binarySearch(a,12) //在数组a中找元素12
7.二维数组
int[][] a = new int[3][];
a[0] = new int[2];
a[1] = new int[4];
a[2] = new int[3];
int[][] a = { { 1, 2, 3 }, { 3, 4 }, { 3, 5, 6, 7 } };
8.冒泡
for (int i = 0; i < values.length; i++) {
for (int j = 0; j < values.length - 1 - i; j++) {
if (values[j] > values[j + 1]) {
temp = values[j];
values[j] = values[j + 1];
values[j + 1] = temp;
}
}
}
9.二分法
public static int binarySearch(int[] array, int value){
int low = 0;
int high = array.length - 1;
while(low <= high){
int middle = (low + high) / 2;
if(value == array[middle]){
return middle; //返回查询到的索引位置
}
if(value > array[middle]){
low = middle + 1;
}
if(value < array[middle]){
high = middle - 1;
}
}
return -1; //上面循环完毕,说明未找到,返回-1
}
本文详细讲解了Java中数组的声明、初始化(静态和动态)、默认值、遍历、拷贝、排序、二分查找等核心内容,包括二维数组、冒泡排序、二分法查找,并展示了Man类在数组排序中的应用。
715

被折叠的 条评论
为什么被折叠?



