5. Java Core Arrays

Insert image description here

1.Array

concept:

​Refers to a container that can store multiple values ​​of the same data type at the same time.

​ But when the array container stores data, it needs to be considered with implicit conversion.

for example:

​ Defines an array of type int. So boolean. Double type data cannot be stored in this array.

​ But data of byte type, short type, and int type can be stored in this array.

suggestion:

The class of the container is consistent with the type of data stored.

Example:

​The integers 1 2 3 4 56 can be stored using an array of type int.

​ Decimals 1.1 1.2 1.3 1.4 can be stored using a double type array.

​ The string "aaa" "bbb" "ccc" can be stored using an array of String type.

2. Definition of array

Format one:

​ Data type [] array name

For example: int [] array

Format two:

​ Data type array name []

For example: int array []

Detailed explanation:

Data type: Limits what type of data the array can store in the future.

Square brackets: Indicates that an array is being defined.

Array name: It’s just a name for future use.

important point:

​The method brackets and the array name are the same whether they are written first or last.

​Usually use the first method habitually.

3. Static initialization of arrays

Full format:

​ Data type [] array name = new data type [] {element 1, element 2, element 3, element 4...};

for example:

​ int[] arr = new int[]{11,22,33};

​ double[] arr = new double[]{1.1,1.2,1.3};

Detailed explanation of format:

Data type: Limits what type of data the array can store in the future.

​ Square brackets: Indicates that what is defined is an array.

​ Array name: It is actually just a name, which is convenient for future use. Follow the camel case naming method when naming.

​ arr namesArr

​ new: It is to open up a space in the memory for the array.

Data type: Limits what type of data the array can store in the future.

The data types in the front and back must be consistent.

​ int[] arr = new double[]{11,22,33};//wrong writing

​ Square brackets: Indicates that what is defined is an array.

Curly brackets: represent the elements in the array. The elements are the data stored in the array.

Multiple elements must be separated by commas.

important point:

  • The data types before and after the equal sign must be consistent.
  • Once an array is created, its length cannot change.

Simplified format:

​ Data type [] array name = {element 1, element 2, element 3, element 4...};

for example:

​ int[] array = {1,2,3,4,5};

​ double[] array = {1.1,1.2,1.3};

Exercise 1:

Define an array to store the ages of 5 students.

1.给数组限定什么类型? int
2.利用静态初始化完成创建并添加元素
int[] agesArr = new int[]{
    
    18,19,20,21,22};
int[] agesArr = {
    
    18,19,20,21,22};

Exercise 2:

Define an array to store the names of 3 students.

1.给数组限定什么类型? String
2.利用静态初始化完成创建并添加元素
String[] namesArr = new String[]{
    
    "zhangsan","lisi","wangwu"};
String[] namesArr = {
    
    "zhangsan","lisi","wangwu"};

Exercise 3:

Define an array to store the heights of 4 students.

1.给数组限定什么类型? double
2.利用静态初始化完成创建并添加元素
double[] heightsArr = new double[]{
    
    1.85,1.82,1.78,1.65};
double[] heightsArr = {
    
    1.85,1.82,1.78,1.65};

4.Address value

int[] arr = {
    
    1,2,3,4,5};
System.out.println(arr);//[I@6d03e736

double[] arr2 = {
    
    1.1,2.2,3.3};
System.out.println(arr2);//[D@568db2f2

When printing an array, what actually appears is the address value of the array.

The address value of the array: represents the location of the array in memory.

Take [I@6d03e736 as an example:

[: Indicates that what is being printed is an array.

I: Indicates that the array printed now is of type int.

@: Just a spacer symbol.

6d03e736: It is the real address value of the array in memory. (hexadecimal)

However, we are accustomed to calling the whole [I@6d03e736] the address value of the array.

The address value is of little use to us when we come to Beijing. It is simple to understand.

5. Array element access

Format:

​Array name[index];

effect:

  • Get the value at the corresponding index in the array

  • Modify the value at the corresponding index in the array

    Once modified, the original value will be overwritten.

Code example:

public class ArrDemo2 {
    
    
    /*

        数组中元素访问的格式:
                数组名[索引];

         作用:
            1.获取指定索引上对应的元素
            2.修改指定索引上对应的元素


    */
    public static void main(String[] args) {
    
    
       int[] arr = {
    
    1,2,3,4,5};
       //需求1:获取arr数组中,3索引上的值
        int number = arr[3];
        System.out.println(number);
        System.out.println(arr[3]);

       //需求2:将arr数组中,3索引上的值修改为10
            arr[3] = 10;
        System.out.println("修改之后为:" + arr[3]);

    }
}

6.Index

​Also called corner subscript and subscript

​ It is the number corresponding to each small grid in the array container.

Index features:

  • The index must start from 0.
  • Continuous without interruption.
  • Increase by +1 one by one.

7. Array traversal

Traversal: It is to take out all the contents of the array one by one.

The length of the array: array name.length;

General code:

for(int i = 0; i < arr.length; i++){
    
    
    //在循环的过程中,i依次表示数组中的每一个索引
    sout(arr[i]);//就可以把数组里面的每一个元素都获取出来,并打印在控制台上了。
}

8. Dynamic initialization of arrays

Format:

​ Data type [] array name = new data type [array length];

Example:

//1.定义一个数组,存3个人的年龄,年龄未知
int[] agesArr = new int[3];


//2.定义一个数组,存班级10名学生的考试成绩,考试成绩暂时未知,考完才知道。
int[] scoresArr = new int[10];

Default initialization values ​​for arrays:

Integer type: 0

Decimal type: 0.0

Boolean type: false

Character type: ‘\u0000’

Reference type: null

9. The difference between the two initialization methods of arrays

Static initialization: int[] arr = {1,2,3,4,5};

Dynamic initialization: int[] arr = new int[3];

Static initialization: manually specify the elements of the array, and the system will calculate the length of the array based on the number of elements.

Dynamic initialization: manually specify the array length, and the system will give a default initialization value.

scenes to be used:

Only the number of elements is specified, but the specific data is not specified. It is recommended to use dynamic initialization.

All data to be manipulated has been identified, and static initialization is recommended.

Example:

  • Use an array to store 5 integers entered from the keyboard.

    int[] arr = new int[5];

  • Store the scores of students in the whole class into an array. The known student scores are: 66,77,88,99,100

    int[] arr = new int[5];

    arr[0] = 66;

    arr[1] = 77;

    … Although it can be achieved, it is too troublesome.

    It is recommended to use static initialization: int[] arr = {66,77,88,99,100};

10. Frequently Asked Questions about Arrays

When an index that does not exist in the array is accessed, an index out of bounds exception will be thrown.

avoid:

​ For any array, the index range:
Minimum index: 0
Maximum index: the length of the array - 1
​Array name.length - 1

public class ArrDemo6 {
    
    
    public static void main(String[] args) {
    
    
       int[] arr = {
    
    1,2,3,4,5,5,5,5,5};
        //用索引来访问数组中的元素
        System.out.println(arr[1]);
        System.out.println(arr[10]);//ArrayIndexOutOfBoundsException

    }
}

11. Array exercises

Exercise 1: Summing

Requirements: Define an array to store 1,2,3,4,5

Traverse the array to get each element, and find the sum of all the data in the array

Code example:

/*定义一个数组,存储1,2,3,4,5
        遍历数组得到每一个元素,求数组里面所有的数据和*/


//分析:
//1.定义一个数组,并添加数据1,2,3,4,5
int[] arr = {
    
    1,2,3,4,5};

//求和变量
int sum = 0;
//2.遍历数组得到每一个数据,累加求和
for (int i = 0; i < arr.length; i++) {
    
    
    //i 依次表示数组里面的每一个索引
    //arr[i] 依次表示数组里面的每一个元素
    sum = sum + arr[i];
}

//当循环结束之后,sum的值就是累加之后的结果
System.out.println(sum);

Exercise 2: Count the numbers

Requirements: Define an array to store 1,2,3,4,5,6,7,8,9,10

Traverse the array to get each element, and count how many numbers there are in the array that are divisible by 3.

Code example:

//分析:
//1.定义一个数组 存储1,2,3,4,5,6,7,8,9,10
int[] arr = {
    
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
//定义一个变量,用来统计次数
int count = 0;
//2.遍历数组得到每一个元素
for (int i = 0; i < arr.length; i++) {
    
    
    //i 表示数组里面的每一个索引
    //arr[i] 表示数组里面的每一个元素
    //3.判断当前的元素是否为3的倍数,如果是那么统计变量就需要自增一次。
    if(arr[i] % 3 == 0){
    
    
        // System.out.println(arr[i]);
        count++;
    }
}
//当循环结束之后,就表示数组里面所有的数字都判断完毕了,直接打印count即可
System.out.println("数组中能被3整除的数字有" + count + "个");

Exercise 3: Varying data

need:

Define an array to store 1,2,3,4,5,6,7,8,9,10

Iterate through the array to get each element.

Require:

1. If it is an odd number, double the current number.

2. If it is an even number, change the current number to half

Code example:

//分析:
//1.定义一个数组,存1,2,3,4,5,6,7,8,9,10
int[] arr = {
    
    1,2,3,4,5,6,7,8,9,10};
//2.遍历数组得到每一个元素
for (int i = 0; i < arr.length; i++) {
    
    
    //i 依次表示数组里面的每一个索引
    //arr[i] 依次表示数组里面的每一个元素
    //3.对每一个元素进行判断
    if(arr[i] % 2 == 0){
    
    
        //偶数 变成二分之一
        arr[i] = arr[i] / 2;
    }else{
    
    
        //奇数 扩大两倍
        arr[i] = arr[i] * 2;
    }
}

//遍历数组
//一个循环尽量只做一件事情。
for (int i = 0; i < arr.length; i++) {
    
    
    System.out.println(arr[i]);
}

Exercise 4: Find the maximum value

Requirement: Find the maximum value in the array

Code example:

//定义数组求最大值:33,5,22,44,55

//扩展问题:
//1.根据求最大值的思路,自己改写一下求最小智
//2.为什么max要记录为arr[0],默认值不能为0吗?
//不能写0
//max的初始化值一定要是数组中的值。
//3.循环中开始条件一定是0吗?
//循环的开始条件如果为0,那么第一次循环的时候是自己跟自己比了一下,对结果没有任何影响,但是效率偏低
//为了提高效率,减少一次循环的次数,循环开始条件可以写1.


//1.定义数组用来存储5个值
int[] arr = {
    
    33,5,22,44,55};
//2.定义一个变量max用来存储最大值
//临时认为0索引的数据是最大的
int max = arr[0];
//3.循环获取数组中的每一个元素
//拿着每一个元素跟max进行比较
for (int i = 1; i < arr.length; i++) {
    
    
    //i 索引  arr[i] 元素
    if(arr[i] > max){
    
    
        max = arr[i];
    }
}
//4.当循环结束之后,max记录的就是数组中的最大值
System.out.println(max);//55

Exercise 5: Count the numbers

Requirement: Generate 10 random numbers between 1 and 100 and store them in an array.

1) Find the sum of all data

2) Find the average of all data

3) Count how many data are smaller than the average

Code example:

//分析:
//1.定义数组
int[] arr = new int[10];
//2.把随机数存入到数组当中
Random r = new Random();

for (int i = 0; i < arr.length; i++) {
    
    
    //每循环一次,就会生成一个新的随机数
    int number = r.nextInt(100) + 1;
    //把生成的随机数添加的数组当中
    //数组名[索引] = 数据;
    arr[i] = number;
}


// 1)求出所有数据的和
//定义求和变量
int sum = 0;
for (int i = 0; i < arr.length; i++) {
    
    
    //循环得到每一个元素
    //并把元素累加到sum当中
    sum = sum + arr[i];
}
System.out.println("数组中所有数据的和为:" + sum);


//2)求所有数据的平均数
int avg = sum / arr.length;
System.out.println("数组中平均数为:" + avg);



//3)统计有多少个数据比平均值小
int count = 0;
for (int i = 0; i < arr.length; i++) {
    
    
    if(arr[i] < avg){
    
    
        count++;
    }
}

//当循环结束之后,就表示我已经找到了所有的比平均数小的数据
System.out.println("在数组中,一共有" + count + "个数据,比平均数小");



//遍历数组,验证答案
for (int i = 0; i < arr.length; i++) {
    
    
    System.out.print(arr[i] + " ");
}

Exercise 6: Exchanging data

Requirement: Define an array and store 1,2,3,4,5. Exchange the elements corresponding to the index as required.

Before exchange: 1,2,3,4,5

After swapping: 5,2,3,4,1

Code example:

//1.定义数组存储数据
int[] arr = {
    
    1,2,3,4,5};
//2.利用循环去交换数据
for(int i = 0,j = arr.length - 1; i < j; i++,j--){
    
    
    //交换变量i和变量j指向的元素
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}
//当循环结束之后,那么数组中的数据就实现了头尾交换
for (int i = 0; i < arr.length; i++) {
    
    
    System.out.print(arr[i] + " ");
}

Exercise 7: Scramble the data

Requirement: Define an array and store 1~5. It is required to shuffle the order of all data in the array.

Code example:

//1.定义数组存储1~5
int[] arr = {
    
    1, 2, 3, 4, 5};
//2.循环遍历数组,从0索引开始打乱数据的顺序
Random r = new Random();
for (int i = 0; i < arr.length; i++) {
    
    
    //生成一个随机索引
    int randomIndex = r.nextInt(arr.length);
    //拿着随机索引指向的元素 跟 i 指向的元素进行交换
    int temp = arr[i];
    arr[i] = arr[randomIndex];
    arr[randomIndex] = temp;
}
//当循环结束之后,那么数组中所有的数据已经打乱顺序了
for (int i = 0; i < arr.length; i++) {
    
    
    System.out.print(arr[i] + " ");
}

おすすめ

転載: blog.csdn.net/haodian666/article/details/135007966