我正在使用Collections.max(array); 确定所选数组中的最大数字是多少.但是,当我使用它时,我收到错误消息:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method max(Collection<? extends T>) in the type Collections is not applicable for the arguments (int)
at Array_6.main(Array_6.java:23)
Run Code Online (Sandbox Code Playgroud)
我的代码如下:
int input;
int highestNumber = 0;
int arrayNumber = 0;
int[] intArray = new int[10];
System.out.println("This application determines the highest number out of 10 inputed numbers");
System.out.println("Welcome, please input the first number:");
for (int i = 0; i < 10; i++){
System.out.print(i+1 + ": ");
input = TextIO.getlnInt(); // Retrieves input
intArray[i] = input;
}
highestNumber = Collections.max(arrayInt);
System.out.println("Highest Number is " + highestNumber);
Run Code Online (Sandbox Code Playgroud)
编辑
我做了下面推荐的内容和消息
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Type mismatch: cannot convert from int[] to int
Bound mismatch: The generic method max(Collection<? extends T>) of type Collections is not applicable for the arguments (List<int[]>). The inferred type int[] is not a valid substitute for the bounded parameter <T extends Object & Comparable<? super T>>
at Array_6.main(Array_6.java:24)
Run Code Online (Sandbox Code Playgroud)
出现了,所以我将int highestNumber更改为一个数组.然后出现此错误:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Bound mismatch: The generic method max(Collection<? extends T>) of type Collections is not applicable for the arguments (List<int[]>). The inferred type int[] is not a valid substitute for the bounded parameter <T extends Object & Comparable<? super T>>
at Array_6.main(Array_6.java:24)
Run Code Online (Sandbox Code Playgroud)
Collections是集合API的实用程序类. arrayInt是一个数组int与Collections类提供的任何东西完全不兼容
你可以尝试使用......
highestNumber = Collections.max(Arrays.asList(intArray));
Run Code Online (Sandbox Code Playgroud)
它包含intArray在一个List接口中,使其与CollectionsAPI 兼容
正如@LouisWasserman指出的那样,上面的内容将不起作用,因为Collections.max它将取决于Object非原始的Collection.
最简单的解决方案可能是简单地检查输入的每个值,例如....
for (int i = 0; i < 10; i++) {
System.out.print(i + 1 + ": ");
input = TextIO.getlnInt(); // Retrieves input
intArray[i] = input;
highestNumber = Math.max(input, highestNumber);
}
Run Code Online (Sandbox Code Playgroud)
或者您也可以使用Arrays.sort(intArray)排序intArray并简单地挑选数组中的最后一个元素,这将是最高的......
或者你可以创建第二个循环,并通过每个元素的循环中intArray使用Math.max,以找到最大的价值...
或者您可以创建一个List<Integer>集合并添加每个项目intArray,然后使用Collections.max...
或者您可以使用Integer[]数组而不是int[]数组...
或者你可以创建一个List<Integer>集合而不是完全使用数组......