package com.web;
import java.util.Arrays;
public class Test7 {
public static void main(String[] args) {
int[] arr = {
2, 4, 1, 9, 2, 7};
// 打印数组,输出地址值
System.out.println("arr = " + arr);
//arr = [I@5e2de80c
// 数组内容转为字符串 ,排序前
System.out.println(Arrays.toString(arr));//[2, 4, 1, 9, 2, 7]
// 升序排序
Arrays.sort(arr);
//排序后
System.out.println(Arrays.toString(arr));//[1, 2, 2, 4, 7, 9]
// 反向遍历打印
//必须i>=0,若i>0,则少输出一个arr[0] = 1
for (int i = arr.length - 1; i >= 0; i--) {
System.out.println("arr[" + i + "] = " + arr[i]);
}
/*
arr[5] = 9
arr[4] = 7
arr[3] = 4
arr[2] = 2
arr[1] = 2
arr[0] = 1
*/
// 定义随机的字符串
String line = "ysKUreaytWTRHsgFdSAoidq";
char[] chars = line.toCharArray();
// 升序排序
Arrays.sort(chars);
//错误示范
System.out.println("chars = " + chars.toString());//chars = [C@1d44bcfa
//正确示范
System.out.println("chars = " + Arrays.toString(chars));//chars = [A, F, H, K, R, S, T, U, W, a, d, d, e, g, i, o, q, r, s, s, t, y, y]
// 反向遍历打印不要写成了int i = chars.length
for (int i = chars.length - 1; i >= 0; i--) {
if (i==chars.length-1){
System.out.print("chars = "+chars[i]+" ");
//不加contine,多输出一个y
//continue:结束本次循环,继续下一次循环
//break:终止switch或者循环
continue;
}
System.out.print(chars[i] + " ");
}//chars = y y t s s r q o i g e d d a W U T S R K H F A
}
}
Arrays类操作数组的方法
猜你喜欢
转载自blog.csdn.net/djydjy3333/article/details/121251106
今日推荐
周排行