public class Test40 {
public static void main(String[] args) {
//把基本数据类型转换为包装类,称为自动装箱
Integer i1 = new Integer(10);
//把包装类转换为基本数据类型,称为自动拆箱
int i2 = i1.intValue();
Integer i3 = 10; //直接定义一个整型对象赋值为10,简写的方式,建议方式
Integer i4 = new Integer("123"); //可以把数值类的字符串直接赋值给整型包装类,注意:字符串的里面的值必须是数字才行
//把数值字符串转换为int类型;称为转型操作
String num1 = "1234";
int i5 = Integer.parseInt(num1);
Integer i6 = Integer.valueOf(num1);
//int i6 = Integer.valueOf(num1); 也可以直接用int接收,JVM会自动完成拆箱
//面试题:
Integer x1 = new Integer(10);
Integer x2 = new Integer(10);
System.out.println(x1==x2); //false ;双等号== 比较的是地址
System.out.println(x1.equals(x2));//true
Integer x3 = new Integer(128);
Integer x4 = new Integer(128);
System.out.println(x3==x4); //false
System.out.println(x3.equals(x4));//true
Integer x5 = 10;
Integer x6 = 10;
System.out.println(x5==x6); //true
System.out.println(x5.equals(x6));//true
Integer x7 = 128;
Integer x8 = 128;
System.out.println(x7==x8); //false ;Integer类中的享元模式,缓存里的最大值是127,所以超过最大值时就要创建对象了故比较返回false
System.out.println(x7.equals(x8));//true
Integer x9 = 127;
Integer x10 = 127;
System.out.println(x9==x10); //true
System.out.println(x9.equals(x10));//true
}
}
基本数据类型 包装类
int Integer
char Character
float Float
double Double
boolean Boolean
byte Byte
short Short
long Long
方法 描述
byteValue() Byte->byte
doubleVale() Double->double
floatValue() Float->folat
intValue() Integer->int
longValue() Long->long
shortValue() Short->short
转型操作:
在包装类中,可以将一个字符串变为指定的基本数据类型,一般在输入数据时会使用较多
在Integer类中将String 变为 int 型数据:Integer.parseInt(String s)
在Folat类中将String 变为 float 型数据:Float.parseFloat(String s)
注意:转型操作时,字符串必须由数字组成,否则会报错
享元模式:(Flyweight Pattern):它使用共享对象,用来尽可能减少内存使用量以及分享资讯给尽可能多的相似对象;
它适合用于大量对象只是重复因而导致无法令人接收的使用大量内存。通常对象中的部分状态是可以分享。常见做法是把它们放
在外部数据结构,当需要使用时再将它们传递给享元。
运用共享技术有效的支持大量细粒度的对象