ArrayList <type> List name = new ArrayList <type> ();
Collections.sort (ArrayList object);
Collections.sort (ArrayList object, Collections.reverseOrder ());
Collections.reverse (list);
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<Integer>(Arrays.asList(50,80,46));
nums.add(1);
System.out.println(nums); //[50, 80, 46, 1]
//Sort in ascending order with the sort function
Collections.sort(nums);
//Display and confirm
System.out.println(nums); //[1, 46, 50, 80]
//Sort in descending order with the sort function
Collections.sort(nums, Collections.reverseOrder());
//Display and confirm
System.out.println(nums); //[80, 50, 46, 1]
//Get the second value from the list and display it
System.out.println(nums.get(2)); //46
System.out.println("The number of data:" + nums.size()); //The number of data:4
for (int i = 0 ; i < nums.size() ; i++){
int num = nums.get(i);
System.out.print(num+" "); //80 50 46 1
}
}
}
Create a program that outputs the given sequence in reverse order. *Input The input is given in the following format: n a1 a2 . . . an n represents the length of the sequence and ai represents the i-th number. *Output Output the reverse sequence of numbers in one row. Insert a space between the elements of the sequence (note that there is no space after the last number). *Constraints
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n =scanner.nextInt();
ArrayList<Integer> nums = new ArrayList<Integer>();
for(int i=1;i<=n;i++){
int num = scanner.nextInt();
nums.add(num);
}
/*
Sort in ascending order
Collections.sort(nums)
Sort in descending order
Collections.sort(nums, Collections.reverseOrder());
Check size
System.out.println(nums.size());
*/
Collections.reverse(nums);
for (int i = 0 ; i < n ; i++){
if (i==n-1){
System.out.print(nums.get(i));
}
else{
System.out.print(nums.get(i)+" ");
}
}
System.out.println();
}
}
Recommended Posts