Long的比较要用equals而不要用==

 

当Long为常量且常量值小于一个字节时,两个Long指向同一个常量内容;

        Long userId=12L;
        Long authorId=12L; 
        System.out.println(userId==authorId);//true

当Long为常量且常量值大于一个字节(>127)时,两个Long指向不同的常量内容。

        Long userId=130L;
        Long authorId=130L;
        System.out.println(userId==authorId);//false

当Long是引用类型时,比较两个Long的大小,一定要用equals而不能用==

        Long x=new Long(18);
        Long y=new Long(18);
        System.out.println(x==y);//false
        System.out.println(x.equals(y));//true

 

原因:Java 基本类型的包装类的大部分都实现了常量池技术,即Byte,Short,Integer,Long,Character;这5种包装类默认创建了数值[-128,127]的相应类型的缓存数据,但是超出此范围仍然会去创建新的对象。

 

相关文章:

  • 2021-10-03
  • 2018-07-31
  • 2022-12-23
  • 2021-09-29
  • 2021-06-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-06-16
  • 2021-08-10
  • 2022-03-05
  • 2021-07-07
  • 2021-11-18
相关资源
相似解决方案