Java查找数组中最大的数字
我们可以通过对数组进行排序并返回最大数来找到Java中数组中最大的数。让我们看一下在Java数组中查找最大数字的完整示例。
public class LargestInArrayExample{
public static int getLargest(int[] a, int total){
int temp;
for (int i = 0;i <total;i++) {
for (int j = i + 1;j <total;j++) {
if (a[i] >a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[total-1];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Largest: "+getLargest(a,6));
System.out.println("Largest: "+getLargest(b,7));
}
}
输出:
使用数组查找数组中的最大数字
让我们看看另一个示例,使用数组获取Java数组中的最大元素。
import java.util.Arrays;
public class LargestInArrayExample1{
public static int getLargest(int[] a, int total){
Arrays.sort(a);
return a[total-1];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Largest: "+getLargest(a,6));
System.out.println("Largest: "+getLargest(b,7));
}
}
输出:
使用集合查找数组中的最大数字
让我们看看另一个示例,使用集合来获取Java数组中的最大数字。
import java.util.*;
public class LargestInArrayExample2{
public static int getLargest(Integer[] a, int total){
List <Integer> list=Arrays.asList(a);
Collections.sort(list);
int element=list.get(total-1);
return element;
}
public static void main(String args[]){
Integer a[]={1,2,5,6,3,2};
Integer b[]={44,66,99,77,33,22,55};
System.out.println("Largest: "+getLargest(a,6));
System.out.println("Largest: "+getLargest(b,7));
}
}
输出: