一.什么是数组
数组是一个固定长度的存储相同数据类型的数据结构,数组中的元素被存储在一段连续的内存空间中。
二.定义方式
//第一种:给每个空间分配值
int[] a = {1,2,3,4};
//第二种: 动态赋值,空间给定,默认给值:0
int[] b = new int[5];
//第三种: 综合式
int[] c =new int[]{1,2,3,4};
三.数组的使用
1.访问数组
根据数组的下标进行访问,最大访问为 数组长度-1 (原因:数组的下标是从0开始)。
public class Test {
public static void main(String[] args) {
int[] array = {1,2,3,4,5};
System.out.println(array[3]);
}
}
2.遍历数组
方法一:for循环
public class ArrayDemo {
public static void main(String[] args) {
int []array = {1,2,3,4,5};
for(int i=0;i<array.length;i++){
System.out.print(array[i]+"\t");
}
}
}
运行结果:
方法二:foreach(加强性for循环)
package Test;
public class ArrayDemo {
public static void main(String[] args) {
int []array = {1,2,3,4,5};
for(int x:array){
System.out.print(x+"\t");
}
}
}
运行结果:
forach的介绍:
foreach是一种循环遍历数组或集合的语法糖,它可以用来简化代码,提高可读性。foreach 的基本语法格式如下:
for(a:array){
//循环体
}
//a是指数组中的元素,array是指要遍历的集合
方法三:toString
package Test;
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
int []array = {1,2,3,4,5};
System.out.print(Arrays.toString(array));
}
}
运行结果:
四.初始化值
五.案例
1.找出数组中的最大值
package Test;
public class ArrayMaxNumDemo {
public static void main(String[] args) {
int[] a = {1, 5, 9, 3, 4, 7, 6, 16, 34, 12, 3};
//先假设数组的第一个值是最大值
int max = a[0];
//利用循环遍历,将假设的最大值与数组中的每一个值进行比较
for (int i = 1; i < a.length; i++) {
//若有比假设值更大,则替换;否则,不变
if(max<a[i]){
max=a[i];
}else{
}
}
System.out.println(max);
}
}
2.找出数组中的第二大值
package Test;
public class ArrayMaxNumDemo {
public static void main(String[] args) {
int[] a = {1, 5, 9, 3, 4, 7, 6, 16, 34, 12, 3};
int max = a[0];//最大值
int sec = a[1];//第二大值
if(sec > max){
int i = max;
max = sec;
sec = i;
}
for (int i = 2; i < a.length; i++) {
if(max<a[i]){
sec = max;
max=a[i];
}else if(a[i] < sec){
continue;
}else{
sec = a[i];
}
}
System.out.println(sec);
}
}