1.方法的重载 (在同一个类中,方法名相同但参数列表不同的方法叫做方法的重载)
2.类中方法的调用:
public class Demo1 {
public static void main(String[] args) {
int a = 5;
int b = 2;
int c = 6;
getMax(a,b,c);
getMax();
}
//求两个数的最大值
public static int getMax(int a, int b) {
return a > b ? a : b ;
}
//求三个数的最大值
public static int getMax(int a, int b,int c) {
//使用已经写好的2个数求最大值的方法
int max = getMax(a, b);
return getMax(max, c);
}
//求四个数的最大值
public static int getMax(int a, int b,int c,int d) {
//使用已经写好的3个数求最大值的方法
int max = getMax(a, b, c);
return getMax(max, d);
}
//求五个数的最大值
public static int getMax(int a, int b,int c,int d,int e) {
//使用已经写好的4个数求最大值的方法
int max = getMax(a, b, c, d);
return getMax(max, e);
}
}
2.数组:可以存放一组相同类型数据的容器,根据下标存放数据,下标从0开始。数组是引用数据类型
2.1 数组的定义:数据类型[ ] 数组名 = 初始化值
//数组的形式1:
double[] arr1 = new double[3];//数组长度一旦限定不可更改
//数组的形式2:
int[] arr2 = new int[] {1, 2, 3};//定义数组的同时初始化数组元素的值
//简便定义数组形式
int[] arr3 = {1,2,3};
3.堆内存特点:1.有默认的初始值
2.有地址
3.有垃圾回收机制
栈内存特定:程序执行完会执行弹栈
4.数组的处理方法
4.1遍历并打印数组
public static void printArr(int[] arr) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
System.out.print(arr[arr.length - 1] + "]");
}else {
System.out.print(arr[i] + ", ");
}
}
System.out.println();
}
4.2 数组的选择排序
public static void selectionSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i; j < arr.length - 1; j++) {
if (arr[i] > arr[j + 1]) {
int temp = arr[i];
arr[i] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
4.3 数组的冒泡排序
public static void popSort(int[] arr) {
for (int i = 0 ;i < arr.length - 1;i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
5. 数组处理中常见的异常
数组越界异常 ArrayIndexOutOfBoundsException
空指针异常 NullPointerException