在Java ArrayList中查找max元素

Bri*_*own 2 java arrays indexing arraylist max

我有这么简单的代码:

import java.util.ArrayList;
import java.util.List;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Integer[] tab = {2324,1,2,2324,3,45,1,5,0,9,13,2324,1,3,9,8,4,2,1};
        Integer max = 2324;
        List<Integer> indexes = new ArrayList<Integer>();
            for (int e = 0; e < tab.length; e++) {
                if (tab[e] == max) {
                    indexes.add(new Integer(e));
                    System.out.println("Found max");
                }
            }
    }
}
Run Code Online (Sandbox Code Playgroud)

这里的主要问题是我想在我tabmax值中找到每个索引.现在,它不起作用 - 它甚至没有显示发现最大消息一次,虽然它应该做3次.那问题呢?

好的,这终于奏效了,谢谢你们所有人:

public static void main(String[] args) {
        Integer[] tab = {2324,1,2,2324,3,45,1,5,0,9,13,2324,1,3,9,8,4,2,1};
        Integer max = 2324;
        List<Integer> indexes = new ArrayList<Integer>();
            for (int e = 0; e < tab.length; e++) {
                if (tab[e].intValue() == max.intValue()) {
                    indexes.add(Integer.valueOf(e));
                    System.out.println("Found max");
                }
            }
    }
Run Code Online (Sandbox Code Playgroud)

jlo*_*rdo 9

更改

Integer[] tab = {2324,1,2,2324,3,45,1,5,0,9,13,2324,1,3,9,8,4,2,1};
Run Code Online (Sandbox Code Playgroud)

int[] tab = {2324,1,2,2324,3,45,1,5,0,9,13,2324,1,3,9,8,4,2,1};
Run Code Online (Sandbox Code Playgroud)

Integer 仅对从-128到127的值预先缓存对象.


如果你想离开,Integer你可以改变

if (tab[e] == max) {
Run Code Online (Sandbox Code Playgroud)

if (tab[e].equals(max)) {
Run Code Online (Sandbox Code Playgroud)

因为它将检查对象是否相等,而不是引用相等.