4.java的数组

1. 数组的排序

1. 冒泡,选择,快速,希尔。。。。

1.冒泡: 两两相比 大的放右面

// 冒泡排序
		// 外层 length-1
		for (int i = 0; i < a1.length - 1; i++) {
			
			// 里层 递减4 3 2 1
			for (int j = 0; j < a1.length - i - 1; j++) {
				if (a1[j] > a1[j + 1]) {
					int r = a1[j];
					a1[j] = a1[j + 1];
					a1[j + 1] = r;
				}
			}
		}

2. 选择排序: 第一位和剩下所有比较,小的放第一位

		int[] a1 = {4,  2,  5, 3, 1}; //;
		a1 = new int[100];
		Random rand = new Random();
		
		for (int i = 0; i < a1.length; i++) {
			a1[i] = rand.nextInt(100);
		}
		// 外层 length-1
		for (int i = 0; i < a1.length - 1; i++) {
			// 里层 
			for (int j = 0; j < a1.length - i - 1; j++) {
				
				if (a1[i] > a1[i + j + 1]) {
					int r = a1[i];
					a1[i] = a1[i + j + 1];
					a1[i + j + 1] = r;
				}
			}
		}
		for (int item: a1) {
			System.out.println(item);
		}

3. 数组常用方法:

Arrays: 工具类(特性:都是静态方法static修饰)。数组的操作

  • Arrays.sort(数组): 升序排序,快速排序

  • int Arrays.binarySearch(数组); 二分查找

  • **System.arraycopy(元数组,元数组起始位置,目标数组, 目标数组起始位置, 长度); **

4. 二维数组:

:::元素是一维数组的:::

​ {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}

在这里插入图片描述

1. 二维数组的定义:


		
		// 二维数组定义 方式一
		int[][] a1 = {{1, 2, 3}, {4, 5, 6, 8, 0, 100}, {7, 8, 9}};
		
		// ★二维数组的遍历 
//		a1[i][j]
		for (int i = 0; i < a1.length; i++) {
			for (int j = 0; j < a1[i].length; j++) {
				System.out.print(a1[i][j] + "\t");
			}
			System.out.println();
		}
		
		System.out.println(a1);
		System.out.println(a1[0]);
		System.out.println(a1[1]);
		System.out.println(a1[2]);
		
		// 不规则数组定义 
		//  {{1, 2, 3}, {4, 5, 6, 8, 0, 100}, {7, 8, 9}};
		int[][] a2 = new int[3][]; // { null, null, null}
		a2[0] = new int[3];
		a2[1] = new int[6];
		System.out.println(a2[0]); // null
		System.out.println(a2[0][0]); // nullpointerException空指针
		
		// 规则数组定义
		int[][] a3 = new int[3][3]; // {{0,0,0},{0,0,0},{0,0,0}}
		System.out.println(a3[0]); // 地址
		System.out.println(a3[0][0]); // 0
		
	

2. ★二维数组的内存、

在这里插入图片描述

5. 类的定义与方法的定义

1.类定义

package 所在包

import …; 调用 其他包的类(java.lang默认包不需要import)

// 类名首字母大写

【public】 class 类名 {

​ // 全局变量

​ int i = 10;

​ // 方法

​ public static void main(String[] args) {

​ // 局部变量

​ int i = 10;

​ }

}

2 方法的定义

public static void main(String[] args) {

​ // 方法体

}

【权限访问修饰符】 【static】 返回修饰-类型|void 方法名标识符 (参数列表){

​ return 值; // 方法有返回值一定要return (方法的结束)

}

{

​ // 方法体

}

【权限访问修饰符】 【static】 返回修饰-类型|void 方法名标识符 (参数列表){

​ return 值; // 方法有返回值一定要return (方法的结束)

}

posted @ 2021-04-10 12:15  剑心空明  阅读(1)  评论(0编辑  收藏  举报  来源