The fourth day of learning java-java array

java array

The string calculated in the memory address of this object returned when the java array is printed The
following code is the string calculated based on the address, which is different from what you imagined;

public class arr {

public static void main(String[] args) {
	int[] number = new int[3];
	number[0] = 2;
	number[2] = 3;
	System.out.println(number);
}

}

Insert picture description here
So you need to introduce a class, import java.util.Arrays;

package arr;

import java.util.Arrays;

public class arr {

public static void main(String[] args) {
	int[] number = new int[3];
	number[0] = 2;
	number[2] = 3;
	System.out.println(Arrays.toString(number));
}

}

The result is as follows:
Insert picture description here
the method of creating and reinitializing is more troublesome. Of course, there is a better way. If you know what elements are, use curly braces to enclose these elements.
code show as below:

package arr;

import java.util.Arrays;

public class arr {

public static void main(String[] args) {
	int[] number = {1,3,5,4,9};
	System.out.println(number.length);
	System.out.println(Arrays.toString(number));
}

}

To expand, the java array sorting
code is as follows:

package arr;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class arr {

public static void main(String[] args) {
	int [] nums = {1,5,8,6,7};
    // 使用java8 Stream流 将数组转换成 集合
    List<Integer> collect = Arrays.stream(nums).boxed().collect(Collectors.toList());
    // 默认升序
    Collections.sort(collect);
    System.out.println("升序 :  " + collect);
    // 通过 reverse 翻转集合中的元素, 实现降序
    Collections.reverse(collect);
    System.out.println("降序 :  " + collect);

}

}

result:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44023710/article/details/113031417