Java: A wrapper class for basic data

Wrapping class encapsulates basic data types

		//基本数据类型和他们各自包装类的对应关系
		byte -- java.lang.Byte
		short -- java.lang.Short
		int  -- java.lang.Integer
		long -- java.lang.Long
		float -- java.lang.Float
		double  -- java.lang.Double
		char  -- java.lang.Character
		boolean -- java.lang.Boolean

Conversion relationship:

		// int --> Integer  两种方式
		Integer a = new Integer(22);
		Integer b = Integer.valueOf(22);
		
		// Integer --> int
		int c = a.intValue();
		
		// 把字符串转换为int(字符串须为纯数字)
		int d = Integer.parseInt("123");
		
		//把字符串转换为double(字符串须为纯数字)
		double d1 = Double.parseDouble("12.3");
		
		// int值转换为二进制的字符串
		String s1 = Integer.toBinaryString(10);

		// int值转换为16进制的字符串
		String s2 = Integer.toHexString(30);
		
		// int值转换为8进制的字符串
		String s3 = Integer.toOctalString(10);
		
		// String转Integer,参数字符串必须为纯数字
		Integer i1 = Integer.valueOf("123");
		Integer i2 = new Integer("12313");
		

Automatic boxing, automatic unboxing (taking Integer and int as examples)

After java1.5 version, automatic boxing and automatic unboxing have been introduced. Automatic boxing refers to the conversion of basic data types to corresponding packaging classes, and automatic unboxing refers to the automatic conversion of packaging classes to basic data types, which are all done at compile time.

//自动装箱,
//编译完后就等于是 : Integer i2  = Integer.valueOf(222);
Integer i1 = 222;

Integer i2 = new Integer(28);
int i3 = i2; //自动拆箱

Before 1.5, boxing and unboxing were like this

Integer i1 = new Integer(223); //装
Integer.valueOf(2222);//装

Integer i2 = new Integer(28);
int i3 = i2.intValue(); //拆箱

The underlying principle of Integer's boxing:


public static Integer valueOf(int i) {
    
    
	if (i >= IntegerCache.low && i <= IntegerCache.high)
	      return IntegerCache.cache[i + (-IntegerCache.low)];
	return new Integer(i);
}

Looking at the source code, we can understand that in the memory, there is an Integer[] array with 256 objects, and the int values ​​in the objects are -128, -127...126,127, respectively, stored in the space with subscripts 0~255 . If the value we pass in is between -128 and 127, we go directly to the cache array to find the corresponding object, without recreating the Integer object. If the value is not in this range, we will create one in the heap memory through the new keyword Object.

Integer i1 = 123;
Integer i2 = 123;
//true , i1和i2两个引用都保存同一块内存地址
//123在-127~128中,缓冲区就有数据,i1和i2两个引用都指向这个对象
System.out.println(i1 == i2);
		// Integer i3 = 128;
		// 等于 Integer i3 = Integer.valueOf(128);
		//但是128不在-128~127范围内,那麽这个对象就不会被保存在常量池中,而是保存在了堆内存
		//所以i3和i4指向的两个对象,不在一个地址
		//使用 == 判断,也就是false
		Integer i3 = 128;
		Integer i4 = 128;
		System.out.println(i3 == i4);//false

Guess you like

Origin blog.csdn.net/qq_41504815/article/details/112911270