前言
暑期集训第四天讲了数组和方法。
数组
数组Array是一个封装类,所以数组本身带有许多方法。
import java.lang.reflect.Array;
public class Test02 {
public static void main(String[] args) {
int[] a = {};
int[] b = new int[]{};
int[] c = {1, 2, 3};
int[] d = new int[5];
int[] e = new int[]{1, 2, 2, 3};
int[][] f = {{}, {}};
int[][] g = new int[3][];
int[][] h = new int[3][2];
}
}
这是最简单的静态数组,静态数组申明之后长度确定,因此设计出了动态数组。
import java.lang.reflect.Array;
import java.util.Arrays;
public class Test02 {
private static int[] data;
private int[] data1;
public static void main(String[] args) {
Test02 T=new Test02();
//int[] a = {};
int[] b = new int[]{};
int[] c = {1, 2, 3};
int[] d = new int[4];
d[0]=0;
d[1]=1;
int[] e = new int[]{4, 3, 2, 1};
int[][] f = {{}, {}};
int[][] g = new int[3][];
int[][] h = new int[3][2];
Arrays.sort(a);
Arrays.sort(data);
Arrays.sort(T.data1);
Arrays.sort(T.data);
Arrays.sort(e,0,2);
Arrays.fill(data,1);
Arrays.fill(T.data1,1);
Arrays.fill(T.data,1);
Arrays.fill(d,0,1,2);
}
}
其中private数组就是动态数组
Arrays有许多自己的方法,例如fill是在末尾加入一个值,sort是升序排序等,在遇到不知道干什么用的方法时,记得查看源码!
稀疏数组
适用于数组内大部分值都是同一个值
用于记录数组一共几行几列,再把不同值的元素记录在一个小规模的数组内,起到节约空间作用。
方法
方法是面向对象的称呼,对于面向对象的语言,我们叫他函数
方法重载
比如,一个输出方法,要求处理输入的数据,再输出一串相应的数字,但是,你打进去的数字可能是数字格式也可能是字符串格式,也可能啥也没打,这时候怎么用一个方法实现呢?
这里我们用到了方法重载
public void A(int a){
System.out.println(a+1);
}
public void A(String a){
System.out.println(Integer.parseInt(a)+1);
}