在老师讲到Inteter时,完全没理解,立即上网查资料,终于明白了。现搬运一位前辈的文章,纯手打。
int 与Integer的区别从大的方面来讲就是基本的数据类型与其包装类的区别。
int是基本的数据类型,直接存数据。而Integer是一个对象,是一个引用指向一个对象。
1.java中的数据类型分为基本的数据类型和复杂的数据类型,int是前者,而Integer是后者。因此int初始化为0;而Integer为null。
2初始化时:
int i=1;
Integer i=new Integer(1);
要把integer当作一个类来使用,但是由于有了自动装箱和拆箱,使得Integer类也可以使用 Integer=1;
int是基本的数据类型。Integer是一个类,是对int的扩展,定义了很多的转换方法,类似的还有 float,Float; double Double; string String;等,而且还提供了处理int类型时非常有用的一些方法和常量。
举个例子:当需要往ArrayList,HashMap中放东西时,像int,double这种内建类型是放不进去的,因为容器都是装 object的,这是就需要这些内建类型的外覆类了。
1.int是基本的数据类型;
2.Integer是int的封装类;
3.int和Integer都可以表示某一个数值;
4.int和Integer不能够互用,因为他们两种不同的数据类型;
举例说明:
ArrayList al=new ArrayList();
int n=40;
Integer nI=new Integer(n);
al.add(n);//不可以
al.add(nI);//可以
总而言之:如果我们定义一个int类型的数,只是用来进行一些加减乘除的运算or作为参数进行传递,那么就可以直接声明为int基本数据类型,但如果要像对象一样来进行处理,那么就要用Integer来声明一个对象,因为java是面向对象的语言,因此当声明为对象时能够提供很多对象间转换的方式,与一些常用的方法。自认为java作为一们面向对象的语言,我们在声明一个变量时最好声明为对象格式,这样更有利于你对面向对象的理解。
public class IntegerDemo {
//基本数据类型的封装类型(引用类型)
//集合框架List Set Map中的元素只能是引用类型
public static void main(String[] args) {
//int Integer可以相互自动转换
//boxing:自动装箱
Integer i1 = 100; //1.4之前error
int i = i1; //unboxing:拆箱
//Integer是引用类型
Integer i2 = new Integer(100);
Integer i3 = new Integer(100);
System.out.println(i2 == i3);
//System.out.println(Integer.valueOf("100")==Integer.valueOf("100"));
//
//常用的对象缓存:-128--127
Integer i4 = 127; //new Integer(127)
Integer i5 = 127; //
System.out.println(i4 == i5);//true
Integer i6 = Integer.valueOf("128");
Integer i7 = Integer.valueOf("128");
System.out.println(i6 == i7);
//Integer上的常用方法,String ==> int
i = Integer.parseInt("123");
//Double.parseDouble("123");
//Float.parseFloat("123.4");
//其它方法
String s1 = Integer.toBinaryString(Integer.MAX_VALUE);
String s2 = Integer.toBinaryString(Integer.MIN_VALUE);
System.out.println(s1);
System.out.println(s2);
}
}