2

我有这样简单的代码:

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");
                }
            }
    }
}

这里的主要问题是我想在我的值tab所在的位置找到每个索引。max现在,它不起作用 - 它甚至不会显示 Found max 消息,尽管它应该执行 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");
                }
            }
    }
4

8 回答 8

9

改变

Integer[] tab = {2324,1,2,2324,3,45,1,5,0,9,13,2324,1,3,9,8,4,2,1};

int[] tab = {2324,1,2,2324,3,45,1,5,0,9,13,2324,1,3,9,8,4,2,1};

Integer对象仅针对从 -128 到 127 的值进行预缓存。


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

if (tab[e] == max) {

if (tab[e].equals(max)) {

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

于 2013-05-13T12:11:57.567 回答
3

那是因为您正在比较 with==和 not equals

于 2013-05-13T12:12:12.637 回答
3

==在不是原始 int 而是 class 实例的情况下使用运算符Integer。基本上,您正在比较两个对象的引用,它们是不同的。尝试使用:

if(tab[e].equals(max))
于 2013-05-13T12:13:18.323 回答
2

JVM 正在缓存整数值。

==仅适用于 -128 到 127 之间的数字

请参阅此处的说明:http ://www.owasp.org/index.php/Java_gotchas#Immutable_Objects_.2F_Wrapper_Class_Caching

于 2013-05-13T12:19:34.010 回答
2

您遇到的基本问题是您使用的是Integer,而不是int 一个区别Integer是对象==将引用对两个不同的对象进行比较。(不是那些对象的内容)

我建议您尽可能使用原语int而不是对象。

于 2013-05-13T12:14:01.023 回答
2

您只能将原始值与==. 由于 Integer 是一个对象,因此更改tab[e] == maxtab[e].equals(max).

寻找equals vs ==

另请阅读:Java:int vs integer

于 2013-05-13T12:14:55.080 回答
1

尝试这个:

if (tab[e].intValue() == max.intValue()) {

或者

if (tab[e].intValue() == max) {

如果您使用的是 Integer 对象而不是原始 int,那么使用像 == 这样的比较运算符,至少一个操作数应该是原始操作数(其他操作数将被隐式转换)。

或者你应该使用equals相等的方法

于 2013-05-13T12:13:50.143 回答
1

使用以下三种之一:1.tab[e].intValue() == max或 2.int max = 2324;或 3. 使用Integer类的equals()方法。

于 2013-05-13T12:13:05.577 回答