class D {
public static void main(String args[]) {
Integer b2=128;
Integer b3=128;
System.out.println(b2==b3);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
false
Run Code Online (Sandbox Code Playgroud)
class D {
public static void main(String args[]) {
Integer b2=127;
Integer b3=127;
System.out.println(b2==b3);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
true
Run Code Online (Sandbox Code Playgroud)
注意:-128到127之间的数字为真.
我是一个新手Java编码器,我只是读取一个整数类的变量,可以在API中描述三种不同的方式.我有以下代码:
if (count.compareTo(0)) {
System.out.println(out_table);
count++;
}
Run Code Online (Sandbox Code Playgroud)
这是一个循环,只是输出out_table.
我的目标是弄清楚如何查看整数值count > 0.
我意识到这count.compare(0)是正确的方法吗?或者是count.equals(0)吗?
我知道这count == 0是不正确的.这是正确的吗?它的价值比较运算符在哪里count=0?
以下代码似乎让我感到困惑,因为它提供了两个不同的输出.代码在jdk 1.7上进行了测试.
public class NotEq {
public static void main(String[] args) {
ver1();
System.out.println();
ver2();
}
public static void ver1() {
Integer a = 128;
Integer b = 128;
if (a == b) {
System.out.println("Equal Object");
}
if (a != b) {
System.out.println("Different objects");
}
if (a.equals(b)) {
System.out.println("Meaningfully equal.");
}
}
public static void ver2() {
Integer i1 = 127;
Integer i2 = 127;
if (i1 == i2) {
System.out.println("Equal Object");
}
if (i1 != i2){
System.out.println("Different objects");
} …Run Code Online (Sandbox Code Playgroud) Map<String,Integer> m;
m = new TreeMap<String,Integer>();
Run Code Online (Sandbox Code Playgroud)
添加以下强制转换只是为了在 m.get() 为空时避免空指针异常是一种好习惯。
System.out.println( ((Integer) 8).equals( m.get("null") ) ); // returns false
Run Code Online (Sandbox Code Playgroud)
或者,使用先前的空检查,它开始看起来有点难看。
System.out.println( m.contains("null") != null && m.get("null").equals( 8 ) );
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来写这个?谢谢。
在Java中整数比较是棘手的,因为int和Integer表现不同.我得到那个部分.
但是,正如此示例程序所示,(Integer)400 (第4行)的行为与(Integer)5 (第3行)不同.为什么是这样??
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.format("1. 5 == 5 : %b\n", 5 == 5);
System.out.format("2. (int)5 == (int)5 : %b\n", (int)5 == (int)5);
System.out.format("3. (Integer)5 == (Integer)5 : %b\n", (Integer)5 == (Integer)5);
System.out.format("4. (Integer)400 == (Integer)400 : %b\n", (Integer)400 == (Integer)400);
System.out.format("5. new Integer(5) == (Integer)5 : %b\n", new Integer(5) == (Integer)5); …Run Code Online (Sandbox Code Playgroud) 我知道我正在比较参考,而我正在使用==这不是一个好主意,但我不明白为什么会发生这种情况.
Integer a=100;
Integer b=100;
Integer c=500;
Integer d=500;
System.out.println(a == b); //true
System.out.println(a.equals(b)); //true
System.out.println(c == d); //false
System.out.println(c.equals(d)); //true
Run Code Online (Sandbox Code Playgroud)