import java.util.List;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int n=scanner.nextInt();
scanner.nextLine();
String[] arr1=scanner.nextLine().split(" ");
//输入:
//5
//1 3 -2 4 5
List<Integer> list1=new ArrayList<>();
int sum=0;
for(int i=0;i<n;i++) {
list1.add(Integer.parseInt(arr1[i]));
sum+=list1.get(i);
}
//最大值
System.out.println(Collections.max(list1)); //5
//最小值
System.out.println(Collections.min(list1)); //-2
//和
System.out.println(sum); //11
//升序
Collections.sort(list1);
System.out.println(list1); //[-2, 1, 3, 4, 5]
//降序:必须先升序再加上逆序
Collections.reverse(list1); //逆序
System.out.println(list1); //[5, 4, 3, 1, -2]
//交换
Collections.swap(list1, 0, 2);
System.out.println(list1); //[3, 4, 5, 1, -2]
//复制法一:
List<Integer> list2=new ArrayList<>();
//初始化list2的长度后,才可以复制
Collections.addAll(list2, new Integer[list1.size()]);
Collections.copy(list2,list1);
list1.set(1, 12);
System.out.println(list1); //[3, 12, 5, 1, -2]
System.out.println(list2); //[3, 4, 5, 1, -2]
//复制法二:
List<Integer> list3=new ArrayList<>(new ArrayList<>(list1));
list1.set(1, 36);
System.out.println(list1); //[3, 36, 5, 1, -2]
System.out.println(list3); //[3, 12, 5, 1, -2]
}
}
Collectons与ArrayList组合的基本使用:求最大值、最小值、和、升序、逆序、降序、交换、复制
最新推荐文章于 2022-11-17 23:27:44 发布