1.一维数组
package ArrayTest;
public class Demo {
public static void main(String[] args) {
int a1[];
int[] a2[];
int a3[] = new int[3];//数组的创建
int a4[] = {1,2,3,4};
int a5[] = new int[] {1,2,3,4,5};//数组的初始化
System.out.println(a5.length);//返回数组的长度
int a6[] = {31,28,31,30,31,30,31,31,30,31,30,31};
for(int i = 0;i<a6.length;i++) {
System.out.println("第"+(i+1)+"月有"+a6[i]+"天");
}
}
}
2.二维数组
package ArrayTest;
public class Dome2 {//春晓的横版与竖版
public static void main(String[] args) {
char a[][] = new char[5][6];
a[1] = new char[]{'春','眠','不','觉','晓',','};
a[2] = new char[]{'处','处','闻','啼','鸟','。'};
a[3] = new char[]{'夜','来','风','雨','声',','};
a[4] = new char[]{'花','落','知','多','少','。'};
System.out.print("---横版---");
for(int i = 0;i<a.length;i++) {
for(int j = 0;j<a[i].length;j++) {
System.out.print(a[i][j]);
}
System.out.println();
}
System.out.println("---竖排排列---");
for(int j = 0;j<6;j++) {
for(int i = 4;i>0;i--) {
System.out.print(a[i][j]);
}
System.out.println();
}
}
}
3.数组的遍历
过于简单,不再赘述
for循环或者foreach循环
4.填充和批量替换数组元素
import java.util.Arrays;
public class Dome3 {
public static void main(String[] args) {
int a[] = new int[5];
Arrays.fill(a, 5);
for(int b :a) {
System.out.println(b);
}
Arrays.fill(a,2,4,7);//替换2~3的数字为7
for(int b :a) {
System.out.println(b);
}
}
}
5.对数组进行排序以及复制
import java.util.Arrays;
public class Dome3 {
public static void main(String[] args) {
int a[] = new int[] {1,2,6,3,8,3};
Arrays.sort(a);//数组升序排列
for(int b:a) {
System.out.print(b);
}
System.out.println();
int b[] = Arrays.copyOf(a, 3);//如果大于原数组长度其余补0
for(int c:b) {
System.out.print(c);
}
System.out.println();
int c[] = Arrays.copyOfRange(a, 2, 4);//复制指定位置
for(int x:c) {
System.out.print(x);
}
}
}
6.冒泡排序
package ArrayTest;
public class Demo {
public static void main(String[] args) {
int a[] = {1,9,3,6,2,5,4,7};
for(int i = 1; i<a.length;i++) {
for(int j = 0;j<a.length-i;j++) {
if(a[j]>a[j+1]) {
int b = a[j];
a[j] = a[j+1];
a[j+1] = b;
}
}
}
for(int c:a) {
System.out.print(c);
}
}
}
7.选择排序
package ArrayTest;
public class Dome2 {
public static void main(String[] args) {
int []a = {1,6,3,9,0,2,5,4,3,10};
int flag;
for(int i = 1;i<a.length;i++) {
flag = 0;
for(int j = 1;j<=a.length-i;j++) {
if(a[flag] < a[j]) {
flag = j;
}
}
int t = a[a.length-i];
a[a.length-i] = a[flag];
a[flag] = t;
}
for(int s:a) {
System.out.print(s+",");
}
}
}