英文:
Why arrayList.contains() returns false for this usecase where as System.out.print() writes same on console?
问题
为什么 arrayList.contains()
对于这个用例返回 false,而 System.out.print()
在控制台上输出相同的结果?
ArrayList<Float> random = new ArrayList<Float>();
random.add(2f);
random.add(4f);
random.add(5f);
random.add(10f);
random.add(99.9f);
System.out.println(random.contains(5.0)); -- 这会返回 false
然而,
System.out.println(random.get(2)); -- 这会返回 5.0
英文:
Why arrayList.contains() returns false for this usecase where as System.out.print() writes same on console ?
ArrayList<Float> random = new ArrayList<Float>();
random.add(2f);
random.add(4f);
random.add(5f);
random.add(10f);
random.add(99.9f);
System.out.println(random.contains(5.0)); -- this returns false
Where as,
System.out.println(random.get(2)); -- this returns 5.0
答案1
得分: 1
在Java中,一个字面的小数是一个double
,即5.0
是一个double
。
contains()
方法期望一个Object
(而不是一个基本数据类型,比如double
),所以Java会将double
自动装箱成一个Double
包装对象,所以你的测试就好像你编写了这样的代码:
System.out.println(random.contains(new Double(5.0))); -- 总是返回false
因为它们是不同的类型,一个Double
永远不会等于一个Float
,所以它总是会返回false
。
然而,你可以编写一个字面的float
,在字面值后面添加一个F
(或f
)。
试试这个:
System.out.println(random.contains(5.0F));
英文:
In Java, a literal decimal is a double
, ie 5.0
is a double
.
The contains()
method expects an Object
(not a primitive, such as double
), so Java autoboxes the double
to a Double
wrapper object, so your test is as if you have coded this:
System.out.println(random.contains(new Double(5.0))); -- always false
Because they are different types, a Double
is never going to be equal to a Float
, so it's always going to be false
.
However, you can code a literal float
, add an F
(or an f
) after the literal.
Try this:
System.out.println(random.contains(5.0F));
答案2
得分: 0
我认为这是因为您正在比较两个浮点数与双精度数,5.0 是一个双精度数。但也可能是两个不同的引用。在这种情况下,这个讨论可能会对您有所帮助:https://stackoverflow.com/questions/18852059/java-list-containsobject-with-field-value-equal-to-x
英文:
I think this is because you are comparing two floats with doubles, 5.0 is a double. But could also be two different references. In which case this discussion may help you: https://stackoverflow.com/questions/18852059/java-list-containsobject-with-field-value-equal-to-x
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论