数组的定义及创建
- 动态初始化 数据类型 [ ] 数组名= new 数据类型[数组长度] 例如:int[] a = new int[5
- 静态初始化 数据类型 [ ] 数组名= new 数据类型[]{ 值1,值2,....} 或 数据类型 [ ] 数组名= { 值1,值2,....} 例如:int[] b = new int[]{1,2,3,4,5}; int[] c = {1,2,3,4,5};
public class TestCreateArry {
public static void main(String[] args) {
int[] a = { 1,2,3 };
char[] b = new char[] {'a','b'};
String[] c= new String[5];
c[0] = "士大夫地方公关部";
//char类型的数组底层代码做了处理,可以直接打印数组具体元素
//其他类型数组需使用工具Arrays.toString(数组名)
System.out.println(a);
System.out.println(Arrays.toString(a));
System.out.println(b);
System.out.println(c);//打印数组地址
System.out.println(Arrays.toString(c));
}
}
数组的扩充容及缩容
public class TestaArrays {
public static void main(String[] args) {
int [] a1 = {1,2,3};
//copyOf()用于数组的复制,两个参数,参数1:所复制数组名,参数2:新数组长度
//copyOfRange 用于数组的截取,三个参数,参数1:所复制数组名,参数2,3复制数组的开始及结束位,含头不含尾
int [] a2 = Arrays.copyOf(a1,8);
int [] a3 = Arrays.copyOfRange(a1, 1, 3);
System.out.println(a1);
System.out.println(Arrays.toString(a1));
System.out.println(a2);
System.out.println(Arrays.toString(a2));
System.out.println(Arrays.toString(a3));
}
}
冒泡排序
public class BubbleSort {
public static void main(String[] args) {
int[] a = { 27,96,73,25,21};
for(int i = 1;i<=a.length - 1;i++) {
for(int j = 0;j<a.length - i;j++) {
if(a[j]>a[j+1]) {
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
System.out.println(Arrays.toString(a));
}
}