Java中数组的最大元素

Java中数组的最大元素,java,arrays,max,Java,Arrays,Max,我想找出数组中最大的元素,我意识到这不是最好的方法,它只在某些情况下有效。如果您能提供一些关于如何更改代码以使其适用于所有实例的建议,我将不胜感激 public static int maxArray(int[] a) { int max = 0; for (int j = 0; j < a.length-1; j++) { if (a[j+1] > a[j]) { max = a[j+1]; } else {

我想找出数组中最大的元素,我意识到这不是最好的方法,它只在某些情况下有效。如果您能提供一些关于如何更改代码以使其适用于所有实例的建议,我将不胜感激

public static int maxArray(int[] a) {
    int max = 0;
    for (int j = 0; j < a.length-1; j++) {
        if (a[j+1] > a[j]) {
            max = a[j+1];
        } else {
            max = a[j];
        }

    }
    return max;

}
公共静态int-maxArray(int[]a){
int max=0;
对于(int j=0;ja[j]){
最大值=a[j+1];
}否则{
max=a[j];
}
}
返回最大值;
}

您需要将当前元素与最大元素进行比较,而不是与下一个元素进行比较

if (a[j] > max) {
    max = a[j];
}

您需要将当前元素与最大元素进行比较,而不是与下一个元素进行比较

if (a[j] > max) {
    max = a[j];
}

我建议你这样做

max=a[0]开始然后用
j
1
循环到
a.length

a[j]
max
进行比较,即如果
a[j]>max
则设置
max=a[j]

我建议你这样做

max=a[0]开始然后用
j
1
循环到
a.length
。 将
a[j]
max
进行比较,即如果
a[j]>max
则设置
max=a[j]

使用此方法

public static int maxArray(int[] a) {

int max = a[0]; // saves a bit of time

for (int j = 1; j < a.length; j++) {
    if (a[j] > max) {
        max = a[j];
    }

}
return max;
公共静态int-maxArray(int[]a){
int max=a[0];//节省了一点时间
对于(int j=1;j最大值){
max=a[j];
}
}
返回最大值;
}

这是非常快速和简洁的。

使用这种方法

public static int maxArray(int[] a) {

int max = a[0]; // saves a bit of time

for (int j = 1; j < a.length; j++) {
    if (a[j] > max) {
        max = a[j];
    }

}
return max;
public static <T extends Object & Comparable<? super T>> T maxArray(T[] array) {
    return Collections.max(Arrays.asList(array));
}
公共静态int-maxArray(int[]a){
int max=a[0];//节省了一点时间
对于(int j=1;j最大值){
max=a[j];
}
}
返回最大值;
}

这非常快速和简洁。

public static
public static
public static int getMaxElement(int[]elements){
public static <T extends Object & Comparable<? super T>> T maxArray(T[] array) {
    return Collections.max(Arrays.asList(array));
}
int max=元素[0]; 对于(int j=0;j最大值){ max=元素[j]; } } 返回最大值; }
公共静态int getMaxElement(int[]元素){
int max=元素[0];
对于(int j=0;j最大值){
max=元素[j];
}
}
返回最大值;
}

在Java 8中,您可以使用流:

public static int maxArray(int[] a) {
    return Arrays.stream(a).max().getAsInt();
}

在Java 8中,您可以使用流:

public static int maxArray(int[] a) {
    return Arrays.stream(a).max().getAsInt();
}

我会从
j=1
开始循环,循环到
j
,然后检查
a[j]>max
。实际上,通过添加if检查,您已经使
节省了一点时间
比从索引
0
开始并使用
Integer.MIN_值
作为初始最大值要贵一点。您将从
j=1
开始循环,循环到
j
,并检查
a[j]>max
。实际上,通过添加if检查,您已经使
节省了一点时间
比从索引
0
开始并使用
Integer.MIN_值
作为初始最大值要贵一点。我唯一的其他建议是处理null和空数组。即
如果(a==null | | a.length==0)返回null我唯一的另一个建议是处理null和空数组。即
如果(a==null | | a.length==0)返回null
这里是相关问题,这里是相关问题,请注意这是一个
int[]
而不是
T[]
。这是行不通的。还请注意,
T中的
Object
扩展了Object&compariablefor redundancy,max函数的声明是:
public static,我假设您是从中复制的。它就在那里。没有理由在您的示例中使用它。是的,
并添加一个cast以返回:
(T)
请注意,这是一个
int[]
而不是一个
T[]
。这是行不通的。还请注意,
T中的
Object
扩展了Object&compariablefor redundancy,max函数的声明是:
public static,我假设您是从中复制的。它就在那里。没有理由在您的示例中使用它。是的,
并添加一个cast以返回:
(T)