- Java8种数据类型?
答:byte
、short
、 int
、long
、 float
double
、 boolean
、 char
Ps: String 不是基本数据类型
- 装箱和拆箱
答:从Java5开始了自动装箱/拆箱机制,二者可以互相转换。自动装箱是Java编译器在基本数据类型和对应的对象包装类型之间做的一个转化。比如:int
转化为Integer
,反之就是自动拆箱。
原始类型:boolean
、char
、byte
、short
、int
、long
、float
、double
封装类型: Boolean
、Character
、Byte
、Short
、Integer
、Long
、Float
、Double
int
和Interger
的区别
答:
-
int
是Java内置8中基本数据类型之一,Integer
是Java为int
对应引入的包装类型(wrapper class)。 -
Integer
变量必须实例化后才能使用,而int
不需要 -
Integer
实际是对象的引用,当new一个Integer
对象时,实际上是生成一个指针指向对象;而int
则是直接存储数据值 -
Integer
的默认值null,int
默认值为0
题目类型一:
Integer a = new Integer(3); Integer d = new Integer(3); // 通过new来创建的两个Integer对象 Integer b = 3; // 将3自动装箱成Integer类型int c = 3; int c = 3; // 基本数据类型3 System.out.println(a == b); // false 两个引用没有引用同一对象 System.out.println(a == d); // false 两个通过new创建的Integer对象也不是同一个引用 System.out.println(c == b); // true b自动拆箱成int类型再和c比较
当两边都是 Integer 对象时,是引用比较;当其中一个是 int 基本数据类型时,另一个 Integer 对象也会自动拆箱变成 int 类型再进行值比较。
题目类型二:
Integer f1 = 100; Integer f2 = 100; Integer f3 = 150; Integer f4 = 150; System.out.println(f1 == f2); // true,当int在[-128,127]内时,结果会缓存起来 System.out.println(f3 == f4); // false,属于两个对象
首先需要注意的是 f1、f2、f3、f4 四个变量都是 Integer 对象引用,所以下面的 == 运算比较的不是值而是引用。装箱的本质是什么呢?当我们给一个 Integer 对象赋一个 int 值的时候,会调用 Integer 类的静态方法 valueOf,关键代码如下:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
returnnew Integer(i);
}
IntegerCache 是 Integer 的内部类。简单的说,如果整型字面量的值在 - 128 到 127 之间,那么不会 new 新的 Integer 对象,而是直接引用常量池中的 Integer 对象,关键代码:
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
Java对于-128到127之间的数,会进行缓存,Integer i = 127
时,会对127进行缓存,下次再写Integer j = 127
时,则会直接从缓存中取。所以上面的面试题中f1==f2
的结果是 true,而 f3==f4
的结果是 false。
网友评论