原始类型封装后的比较 Integer Short Long

来源:互联网 发布:java常用算法手册 pdf 编辑:程序博客网 时间:2024/05/11 04:52
Integer是对原始类型int的封装。Short是对short的封装。Long是对long的封装.
  1. public class IntegerTest {
  2.     public static void main(String[] args) {
  3.         
  4.         short s = 42;
  5.         
  6.         Long x = new Long("42");
  7.         
  8.         Long y = new Long(42);
  9.         
  10.         Short z = new Short("42");
  11.         
  12.         Short x2 = new Short(s);
  13.         
  14.         Integer y2 = new Integer("42");
  15.         
  16.         Integer z2 = new Integer(42);
  17.         if(x == y){
  18.             
  19.             System.out.println("x == y");
  20.             
  21.         }
  22.         
  23.         if(x.equals(y)){
  24.             
  25.             System.out.println("x.equals(y)");
  26.             
  27.         }
  28.         
  29.         if(x.equals(z)){
  30.             
  31.             System.out.println("x.equals(z)");
  32.             
  33.         }
  34.         
  35.         if(x.equals(x2)){
  36.             
  37.             System.out.println("x.equals(x2)");
  38.             
  39.         }
  40.         
  41.         if(x.equals(z2)){
  42.             
  43.             System.out.println("x.equals(z2)");
  44.             
  45.         }
  46.     }
  47. }
运行结果:
==========================
x.equals(y)

要注意的一点是Integer 不能和诸如 Short类型比较,因为他们属于不同的类型,所以它们不会相等。