数组
数组就是一个存储相同数据类型的容器
数组的特点:
- 数组是定长的
- 数组存储的元素是连续存放的
- 数组存储的元素是按照索引来存储的,并且索引从0开始
- 获取数组长度的属性:length
一维数组
//先声明
//初始化
//使用
//1.声明数组
int[] arrays;//声明一个int型的数组,存储的都是int型的
//2.创建数组(初始化容器大小)
arrays = new int[10]; //当数组的长度固定,这个长度不能再改变
//int[] arrays = new int[]×
//int[] arrays = new int[0]√
//3.初始化数组
//动态初始化
arrays[0] = 12;
arrays[1] = 12;
//静态初始化
int[] arrays = new int[]{2,3,4};
//4.使用数组
创建数组
-
创建数组并给数字每个位置初始化
类型[] 数组名 = {};
-
先声明数组,创建数组,最后通过数组的下标来给数组的每个位置存放元素
类型[] 数组名; 数组名 = new 类型[] {长度}; 数组名[i] = 值;
-
声明数组并创建好数组,最后通过数组的下标来给数组的每个位置存放元素
类型[] 数组名 = new 类型[] {长度}; 数组名[i] = 值;
对于2、3两种创建数组的方法,创建出来的时候都有默认值
byte short int:0
long:0L
float:0.0F
double:0.0
char:’/u0000’’’
boolean:false
数组/对象(引用数据类型):null
遍历数组
for-i遍历
for(int i = 0; i < arrays.length; i++){
sout
}
for-each遍历
for(int i:arrays){
sout
}
for-i和for-each里的元素不一样(i和arrays[i])
数组去重
对一个有序数组进行去重
思路:快慢索引
多维数组
二维数组
一维数组里面存放的是单个数据
int[] arr1 = {1,2,3,4};
int[] arr2 = {{1},{1,2},{1,2,3},{1,2,3,4}};
如何创建二维数组
里面数组的长度是确定的
//1.声明数组
int[] arr1;
int[][] arr1;
//2.创建数组
//在创建的时候指定外层数组的长度
arrays = new int[3][4];
//3.初始化数组
//4.遍历数组
int[][] arrays = {{},{},{}};
里面数组的长度不确定
int[][] arrays = new int[5][];
//这种情况下,不能使用arrays[0][0]= 12;这种方式存储
arrays[0] = new int[12];
for(int i = 0;)
方法
方法就是把一段代码提取出来并取了个名字,提高代码的复用性
在java里,同一个类里,静态方法只能调用静态的方法
main方法是静态的,所以我写的全是静态方法
无返回值:void
有返回值:必须指定该方法的返回值类型
访问修饰符 static 返回值类型 方法名(参数列表){
}
返回值类型:
如果你的方法不需要返回值,则返回值类型写成void
如果有返回值,返回值类型有:byte、short、int、long、float、double、char、boolean、数组 int[]
必须在代码逻辑最后加return 指定返回值
参数是从方法外面带入一些数据进入方法
有返回值是从方法里面带出一些数据出方法
无参无返回值
static void test1(){
}
public static void main(String[] args){
test();
System.out.println(test1()); //对于没有返回值的方法,不能用输出语句(因为没有可打印的参数)
}
无参有返回值
//返回int类型
static int test2(){
if(){
return in值; //分支里的return也能退出整个方法
}
return int值;
}
public static void main(String[] args){
int i = test2();
System.out.println(test2());
}
有参无返回值
static void test3(int i,String j){ //i j为形参 i j类型可以不同
}
public static void main(String[] args){
test3(2,"3");
}
有参有返回值
static void test4(int i,int j){ //i j为形参 i j类型可以不同
int sum = i + j;
return sum;
}
public static void main(String[] args){
test4(2,3);
}
方法、参数的命名规范:小驼峰
一个单词构成:全部小写
多个单词构成:第一个单词的首字符小写,从第二个单词开始首字符都大写
方法的重载(Overload)
在同一个类里面,方法名一样参数列表不一样
参数列表不一样:个数、类型
可变长参数
类型… 参数名
static int test(int ... i){
}
static int test(int[] arr){
}
static int test(){
}
test(); //优先考虑定长参数方法
test(1,1);
test(1,1,....1)
如果你的方法定义了一个可变长参数
要将可变长参数放在最后的位置
static int test(int j, int ... i){ //int ... i, int j ×
}
test(1,1,...,1)
引用数据类型和基本数据类型的区别
如果在方法中,改变基本数据类型的值,在方法外面,其值并未发生改变
但在方法中改变了引用数据类型的值,在方法外面,其值也发生了改变
(String是不可改变的)
int[] arr = new int[]{1,2,3}
int[] arr1 = arr;
arr1[0] = 12;
int a = 12;
int b = a;
b = 14;
sout(b); //b = 14
sout(arr); //a = {12,2,3}