Rookie learning Java array - Part 1

array

insert image description here

insert image description here
Arrays are better suited than variables

statically initialized array

Assign values ​​directly to the array when defining the array.
The format of statically initialized arrays:
insert image description here

package com.ithema.loop;

import java.util.Arrays;

public class demo251 {
    
    
    public static void main(String[] args) {
    
    
        int[] a = new int[] {
    
    1,2,3,4,5,6};
        double[] b = new double[] {
    
    1.1, 2.2, 3.3};
        String[] c = new String[] {
    
    "a1", "a2", "3a"};

        System.out.println(Arrays.toString(a));
        System.out.println(Arrays.toString(b));
        System.out.println(Arrays.toString(c));

        System.out.println("-------------------------------");
        int[] d = {
    
    1,2,3,4,7};
        double[] e = {
    
    11.1, 12.2, 13.3, 14.4};
        String[] f = {
    
    "aa", "bb", "cc"};

        System.out.println(Arrays.toString(d));
        System.out.println(Arrays.toString(e));
        System.out.println(Arrays.toString(f));

    }
}

output

[1, 2, 3, 4, 5, 6]
[1.1, 2.2, 3.3]
[a1, a2, 3a]
-------------------------------
[1, 2, 3, 4, 7]
[11.1, 12.2, 13.3, 14.4]
[aa, bb, cc]

Why can't java output arrays directly?

In Java, System.out.println()functions cannot be used directly to output the contents of an array because arrays are treated as objects in Java. When we try to output an array, we actually call the array's toString()method to get a string representing the array's contents.

By default, array toString()methods return a string representing the memory address of the array, not the actual contents of the array elements. This is because Javaarrays in are passed by reference, not by value. So outputting the array directly shows its references.

If you want to output the contents of the array, you can use Arraysthe static method of the class toString()to convert the array to a string and then output it. For example:

int[] array = {
    
    1, 2, 3, 4, 5};
System.out.println(Arrays.toString(array));

This will output: [1, 2, 3, 4, 5], showing the element contents of the array.

In addition, you can also use a loop to iterate over the array and output the elements of the array one by one. This allows more flexible control over the format and manner of output.

int[] array = {
    
    1, 2, 3, 4, 5};
for (int i = 0; i < array.length; i++) {
    
    
    System.out.println(array[i]);
}

This will output the elements of the array row by row:

1
2
3
4
5

Javacannot output the contents of an array directly because arrays are considered objects, not primitive types. To output the contents of an array, you can use a method Arraysof the class toString()to convert the array to a string, or loop through the array to output the elements one by one.

Dictionaries, Tuples, Sets

Are there any concepts similar to python's dictionaries, tuples, and sets in java?

Yes, Java also has concepts similar to Python's dictionaries, tuples, and sets, although they may be used slightly differently and in syntax. Following are the classes and interfaces corresponding to these concepts in Java:

  • Dictionary (Dictionary): In Java, the concept similar to dictionary is Map. Map is an interface that provides a mapping of key-value pairs. Common Map implementation classes include HashMap, TreeMap, and LinkedHashMap. Use a Map to store and retrieve values ​​based on keys. When referring to dictionary-like concepts in Java, we usually refer to the Map interface and its implementing classes. The Map interface defines a data structure that maps key-value pairs, where keys are unique and values ​​can be repeated. The following is a simple example showing how to use the Map interface and its implementation class HashMap to create, manipulate and access dictionary (key-value pairs) data:
import java.util.HashMap;
import java.util.Map;

public class MapExample {
    
    
    public static void main(String[] args) {
    
    
        // 创建一个Map对象,使用HashMap实现
        Map<String, Integer> scores = new HashMap<>();

        // 添加键值对
        scores.put("Alice", 85);
        scores.put("Bob", 90);
        scores.put("Charlie", 95);

        // 获取键对应的值
        int aliceScore = scores.get("Alice");
        System.out.println("Alice's score: " + aliceScore);

        // 检查键是否存在
        boolean isBobPresent = scores.containsKey("Bob");
        System.out.println("Is Bob present? " + isBobPresent);

        // 修改键对应的值
        scores.put("Charlie", 100);

        // 遍历所有的键值对
        for (Map.Entry<String, Integer> entry : scores.entrySet()) {
    
    
            String name = entry.getKey();
            int score = entry.getValue();
            System.out.println(name + "'s score: " + score);
        }

        // 删除键值对
        scores.remove("Alice");

        // 判断Map是否为空
        boolean isEmpty = scores.isEmpty();
        System.out.println("Is the map empty? " + isEmpty);
    }
}

In the above example, we use HashMap as the implementation class of the Map interface. First, we create a Map object of scores, whose keys are of type String and values ​​of type Integer. Then, we add key-value pairs through the put() method, get the value corresponding to the key through the get() method, and check whether the key exists through the containsKey() method. We can also use the entrySet() method to traverse all key-value pairs, delete the key-value pairs through the remove() method, and check whether the Map is empty through the isEmpty() method.

Running the above example will output the following results:

Alice's score: 85
Is Bob present? true
Alice's score: 85
Charlie's score: 100
Bob's score: 90
Is the map empty? false

This example shows the basic operations of using the Map interface. You can use the Map interface and its different implementation classes to create and operate dictionary data structures according to specific requirements and scenarios.

  • Tuple: There is no built-in tuple type in Java, but you can simulate the behavior of tuples by creating custom classes. You can create a simple POJO (Plain Old Java Object) class to store multiple values ​​and provide corresponding access methods.

For example, suppose you want to create a tuple containing name and age, you can create a class called Person that has name and age properties and corresponding getter and setter methods.

public class Person {
    
    
    private String name;
    private int age;

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }
}

Then, you can create Person objects, and set and get their properties:

Person person = new Person();
person.setName("John");
person.setAge(25);

String name = person.getName();
int age = person.getAge();

  • Set: In Java, a set is a container for a set of unique elements. Java provides several classes that implement the Set interface, such as HashSet, TreeSet, and LinkedHashSet. These classes provide methods for adding, removing, and checking elements in a collection, and ensuring the uniqueness of elements.

For example, you can create a HashSet containing integers and perform common set operations:

Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(3);

System.out.println(set); // 输出: [1, 2, 3]

set.remove(2);

System.out.println(set); // 输出: [1, 3]

It should be noted that Java's collections and dictionaries are generic, which means that you can store specific types of elements in them. You can specify the type of elements in a collection or dictionary and benefit from type safety and compile-time checking when using them.

insert image description here

array access

insert image description here
View the length of the array - how much data is stored
insert image description here

package com.ithema.loop;

import java.util.Arrays;

public class demo251 {
    
    
    public static void main(String[] args) {
    
    
        int[] a  = {
    
    1,2,3};

        System.out.println(a[0]);
        System.out.println(a[2]);
        System.out.println(a[1]);

        a[0] = 100;
        System.out.println(Arrays.toString(a));

        System.out.println(a.length);
        
        int[] b = {
    
    };
        System.out.println(b.length);

    }
}

output

1
3
2
[100, 2, 3]
3
0

How to add an element to the defined array, give a case

In Java, the length of an array is fixed, and its size cannot be changed directly once created. Therefore, it is not possible to directly add elements to an already defined array. However, you can create a new array, copy the elements of the original array into the new array, and add the new elements at the end of the new array. Here is an example:

import java.util.Arrays;

public class AddElementToArrayExample {
    
    
    public static void main(String[] args) {
    
    
        // 原始数组
        int[] originalArray = {
    
    1, 2, 3, 4, 5};

        // 新元素
        int newElement = 6;

        // 创建新数组
        int[] newArray = new int[originalArray.length + 1];

        // 复制原始数组到新数组
        System.arraycopy(originalArray, 0, newArray, 0, originalArray.length);

        // 将新元素添加到新数组的末尾
        newArray[newArray.length - 1] = newElement;

        // 打印新数组
        System.out.println("Original array: " + Arrays.toString(originalArray));
        System.out.println("New array: " + Arrays.toString(newArray));
    }
}

In the above example, we have a defined original array originalArray, which contains some elements. We want to add new element newElement to this array. First, we create a new array newArray whose length is 1 more than the original array to accommodate the new elements. We then copy the elements of the original array into the new array using the System.arraycopy() method. Finally, we put the new element into the last position of the new array. Finally, we print out the contents of the original array and the new array by using the Arrays.toString() method.

Running the above example will output the following results:

Original array: [1, 2, 3, 4, 5]
New array: [1, 2, 3, 4, 5, 6]

In this way, we have successfully added new elements to the already defined array and created a new array containing all elements. Note that the original array itself is not changed, but a new array is created to store the expanded result.

insert image description here

array traversal

insert image description here

Is there any usage similar to try except in python in java?

In Java, there is an exception handling mechanism similar to try-except in Python. Java uses try-catch blocks to catch and handle exceptions. Here is an example:

public class ExceptionHandlingExample {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            // 可能会引发异常的代码
            int result = divide(10, 0);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
    
    
            // 捕获并处理异常
            System.out.println("An arithmetic exception occurred: " + e.getMessage());
        }
    }

    public static int divide(int dividend, int divisor) {
    
    
        return dividend / divisor;
    }
}

In the above example, we defined a divide() method for integer division. In the main() method, we call the divide() method and set one of its operands to 0, which causes an ArithmeticException to be thrown. To catch and handle this exception, we use try-catch block.

In the try block, we place the code that may throw an exception. In this example, we called the divide() method and stored the result in the result variable and tried to print out the result. Since the divisor is 0, an ArithmeticException will be triggered.

In the catch block, we specify the exception type ArithmeticException to catch. When an exception is thrown, the program will jump to the catch block and execute the corresponding processing logic. In this example, we print out the exception message.

Running the above example will output the following results:

An arithmetic exception occurred: / by zero

Through the try-catch block, we can catch and handle the exception that may occur, prevent the program from crashing due to the exception, and take appropriate measures to handle the abnormal situation. In addition to catch blocks, finally blocks can be used to execute code that must be executed whether or not an exception occurs. This ensures that operations such as release and cleanup of resources are handled correctly.

Then say the above traversal

hot key:a.fori + tab

package com.ithema.loop;

public class demo251 {
    
    
    public static void main(String[] args) {
    
    
        int[] a  = {
    
    1,2,3};

        for (int i = 0; i < a.length; i++) {
    
    
            System.out.println(a[i]);
        }

    }
}

output:

1
2
3

another stronger method

package com.ithema.loop;

public class demo251 {
    
    
    public static void main(String[] args) {
    
    
        int[] a  = {
    
    1,2,3};

        for (int j : a) {
    
    
            System.out.println(j);
        }

    }
}

the case

Requirement: The sales of 5 employees in a certain department are: 16, 26, 36, 6, 100, please calculate the total sales of their department.

package com.ithema.loop;

public class demo251 {
    
    
    public static void main(String[] args) {
    
    
        int[] a  = {
    
    16, 26, 36, 6, 100};
        int count = 0;
        for (int j : a){
    
    
            count += j;
        }
        System.out.println("总销售额为: "+count);


    }
}

Dynamically initialize an array

insert image description here

Does the java array have the idea of ​​​​slicing?

In Java, arrays do not have the concept of slicing like in Python. In Java, to get a subarray or partial elements of an array, you need to manually create a new array and copy the required elements into the new array.

Here is an example showing how to get a subarray of an array in Java:

import java.util.Arrays;

public class ArraySlicingExample {
    
    
    public static void main(String[] args) {
    
    
        int[] originalArray = {
    
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

        int startIndex = 2;
        int endIndex = 7;

        int[] subArray = new int[endIndex - startIndex + 1];

        System.arraycopy(originalArray, startIndex, subArray, 0, subArray.length);

        System.out.println("Original array: " + Arrays.toString(originalArray));
        System.out.println("Subarray: " + Arrays.toString(subArray));
    }
}

In the above example, we have an original array originalArray which contains some elements. We want to get a subarray of the original array starting at index startIndex and ending at index endIndex (both elements inclusive). First, we calculate the length of the subarray and create a new subArray array using the new keyword. We then use the System.arraycopy() method to copy the elements of the original array into the subarray. Finally, we print the contents of the original array and subarrays using the Arrays.toString() method.

Running the above example will output the following results:

Original array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Subarray: [3, 4, 5, 6, 7]

This way, we manually take a subarray of the original array and create a new array containing the required elements.

It should be noted that arrays in Java are of fixed length and cannot be sliced ​​directly. If you need to perform frequent slicing operations, you may need to consider using variable-length collection classes such as ArrayList, or write custom tool methods to simplify the process of slicing operations.

Occupy first, assign later

package com.ithema.loop;

import java.util.Arrays;

public class demo251 {
    
    
    public static void main(String[] args) {
    
    
        int[] a = new int[3];
        System.out.println(Arrays.toString(a));
        for (int i = 0; i < a.length; i++) {
    
    
            a[i] = i;
        }
        System.out.println(Arrays.toString(a));

    }
}

output

[0, 0, 0]
[0, 1, 2]

insert image description here

package com.ithema.loop;

import java.util.Arrays;

public class demo251 {
    
    
    public static void main(String[] args) {
    
    
        int[] a = new int[3];
        System.out.println(Arrays.toString(a));

        char[] chars = new char[3];
        System.out.println((int) chars[0]);

        double[] dou = new double[3];
        System.out.println(dou[2]);

        boolean[] fal = new boolean[2];
        System.out.println(fal[1]);

        String[] str = new String[12];
        System.out.println(str[3]);

    }
}

output

[0, 0, 0]
0
0.0
false
null

insert image description here

the case

insert image description here

package com.ithema.loop;

import java.util.Scanner;

public class demo251 {
    
    
    public static void main(String[] args) {
    
    
        double[] score = new double[6];
        Scanner scanner =  new Scanner(System.in) ;
        for (int i = 0; i < score.length; i++) {
    
    
            System.out.println("请输入数字:");
            double data =  scanner.nextDouble();
            score[i] = data;
        }
        double sum = 0;
        for (double j : score){
    
    
            sum += j;
        }
        System.out.println(sum/score.length);
    }
}

output:

请输入数字:
12
请输入数字:
13
请输入数字:
14.
请输入数字:
17.8
请输入数字:
13.
请输入数字:
25.
15.799999999999999

Of course, this program can be directly calculated:

package com.ithema.loop;

import java.util.Scanner;

public class demo251 {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        double avgdate = 0;
        for (int i = 0; i < 6; i++) {
    
    
            System.out.println("请输入数字:");
            double date = scanner.nextDouble();
            avgdate += date;
        }
        System.out.println(avgdate/6);
    }
}

output:

请输入数字:
12
请输入数字:
13
请输入数字:
14.
请输入数字:
17.8
请输入数字:
13.
请输入数字:
25.
15.799999999999999

Guess you like

Origin blog.csdn.net/AdamCY888/article/details/131385126