首页 > 技术文章 > Integer

Yxxxxx 2017-05-08 22:45 原文

Integer 类型的值在[-128,127] 期间,Integer 用 “==”是可以的   , Integer  与 int 类型比较(==)比较的是值。

 

Integer为对象,如果判断相等要用equals,而不能用==。

如果是判断两个int值相等,则可以用==。

 

无论如何,Integer与new Integer不会相等。不会经历拆箱过程,他们的内存地址不一样,所以为false

两个都是非new出来的Integer,如果数在-128到127之间,则是true,否则为false

两个都是new出来的,都为false

int和integer(无论new否)比,都为true,因为会把Integer自动拆箱为int再去比

 

public class Temp {

public static void main(String[] args) {

Integer a=123;
Integer b=123;
System.out.println(a==b);
System.out.println(a.equals(b));

Integer c=128;
Integer d=128;
System.out.println(c==d);
System.out.println(c.equals(d));

Integer e=new Integer(128);
Integer f=new Integer(128);
System.out.println(e==f);
System.out.println(e.equals(f));

int g=128;
System.out.println(g==f);
System.out.println(f.equals(g));
}
}

true
true
false
true
false
true
true
true

 

 

java提供了两种类型:引用类型和原始类型(内置类型)。int是java的原始数据类型,Integer是java为int提供的封装类。
  java为每一种数据类型提供了自己的封装类:
  原始数据类型 封装类
  int Integer
  boolean Boolean
  char Character
  byte Byte
  short Short
  long Long
  float Float
  double Double
  引用类型和原始类型的行为完全不同,并且他们具有不同的语义,引用类型和原始类型具有不同的特征和用法,他们包括:大小和速度问题,这种类型以哪种类型的数据结构存储,当引用类型和原始类型有用作某个类的实例数据时制定的缺省值。对象应用实例变量的缺省值为null,而原始类型实例变量的缺省值与它们的类型有关。

 

 

Integer和int的区别

 

1、Integer是int提供的封装类,而int是Java的基本数据类型;


2、Integer默认值是null,而int默认值是0;


3、声明为Integer的变量需要实例化,而声明为int的变量不需要实例化;


4、Integer是对象,用一个引用指向这个对象,而int是基本类型,直接存储数值。

推荐阅读