本题要求使用 Collection 类的 Collections.max() 来获取向量的最大元素,并输出结果。 样例输入 3 5 2 1 6 7 样例输出 7
时间: 2023-12-03 19:43:11 浏览: 34
好的,可以使用以下代码实现:
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int num = sc.nextInt();
list.add(num);
}
int max = Collections.max(list);
System.out.println(max);
}
}
```
输入时,先读入向量的长度 n,然后使用一个 ArrayList 存储向量的元素。循环读入每个元素后,使用 Collections.max() 方法获取最大值并输出即可。
相关问题
本题要求使用 Collections.reverse() 函数将数组进行反转,并输出结果。 样例输入:1 2 3 5 3 4 7 样例输出:7 4 3 5 3 2 1
可以按照以下步骤来实现:
1. 将输入的字符串转化为数组,可以使用 split() 函数。
2. 使用 Arrays.asList() 函数将数组转化为 List。
3. 使用 Collections.reverse() 函数对 List 进行反转。
4. 遍历反转后的 List,输出每个元素。
下面是示例代码:
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String[] arr = input.split(" ");
List<String> list = Arrays.asList(arr);
Collections.reverse(list);
for (String s : list) {
System.out.print(s + " ");
}
}
}
```
输入样例:
```
1 2 3 5 3 4 7
```
输出样例:
```
7 4 3 5 3 2 1
```
Collections.max
`Collections.max`是Java标准库中的一个静态方法,用于返回一个集合中的最大值。它有两个重载方法:
- `public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)`:返回集合中的最大值。
- `public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp)`:返回集合中的最大值,使用指定的比较器进行比较。
例如,如果我们有一个列表存储了一些整数,我们可以使用`Collections.max`方法获取列表中的最大值:
```
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int max = Collections.max(numbers);
System.out.println(max); // 输出: 5
```
在上面的示例中,我们首先使用`Arrays.asList`方法创建了一个包含整数的列表,然后使用`Collections.max`方法获取列表中的最大值。由于列表中的元素是整数,因此最大值也是一个整数。