Java Short type comparison of the pit

Java Short type comparison of the pit

Premise conventions:

After calculating the time accuracy of less than a value == int operation (when not defined) will be automatically converted to == int


short x = 3;
Short s1 = 2;

if (s1.equals(x - 1)) {
  System.out.println("!!!!!");
}
// 输出:null
  • In fact, the above definition of the x, S1, . 3, and 2 are behind the int type , but the compiler at compile time to help us automatically converted to the corresponding short type.

  • In operation the compiler will not make the above-described conversion, namely: x - 1 becomes the int type , and rewritable type Short equals method as follows:

    • Short !!! goal is not the type of direct returns false
    public boolean equals(Object obj) {
        // !!!目标不是Short类型,直接会返回false
        if (obj instanceof Short) {
            return value == ((Short)obj).shortValue();
        }
        return false;
    }
    

    So there will be no output.

  • The if statement in the change s1.equals((short)(x-1))to

  • Therefore, when using the map should be avoided Short is key, if you must use Short, will have to pay attention to these, otherwise it will go wrong

    The comparison of the incoming key and map elements in the HashMap remove when:

    if (p.hash == hash &&
        ((k = p.key) == key || (key != null && key.equals(k))))// 其中key为外部传入的经过运算后的Short,为Integer,而k为Short
    

    At this time, the second line is determined == false directly, because the type Short Integer and can not be used == comparison, while the back is also equals false, so remove ineffective.

Published 28 original articles · won praise 16 · views 3177

Guess you like

Origin blog.csdn.net/Newbie_J/article/details/104440708