基本类型和包装类型

基本类型与包装类型的区别:boolean 与 Boolean,byte 与 Byte,intInteger,char Character, short Short, long Long,float Float, double Double共八对。这里就说说intinteger的区别吧,其他的类似:

  int是原始类型。它不是对象。int是一种高性能(原因是基本类型都分配在栈中),范围介于Integer.MAX_VALUEInteger.MIN_VALUE之间。占32bit,内容可变,出给你限制他们final.

  Integer是一个对象,它的成员变量value(不好意思,private)代表Integer本身,跟一个int相比,他的体积要大的多。它提供了一些方法包括:intString的互相转化和对int本身的一些处理(比如转化为其他的基本数据:byteValue(),doubleValue())

  哪一种好呢?取决于你想做什么。

 

再看看他们的转换:

// to int i from Integer ii
int i = ii.intValue();

// to Integer ii from int i
Integer ii = new Integer( i );

性能测试

public class IntegerDemo {
	public static void main(String[] args) {
		System.out.println(intTest(100000));
		System.out.println(integerTest(100000));
	}
public static long intTest(int n){
	long start = System.currentTimeMillis();
	int x = 1;
	for(int i=0;i<n;i++)
	x=x+1;
	long end = System.currentTimeMillis();
	return end-start;
}
public static long integerTest(int n){
	long start = System.currentTimeMillis();
	Integer x = 1;
	for(int i = 0;i<n;i++){
		x=x+1;
	}
	long end = System.currentTimeMillis();
	return end-start ;
}
}

 

经验可以积累,但梦想永远不能磨灭
原文地址:https://www.cnblogs.com/lancee/p/2648175.html