包装类
1、基本类型和包装类的区别是什么,什么地方必须要用到包装类?
int 是基本类型,直接存数值 ,Integer是类,产生对象时用一个引用指向这个对象。包装类在堆中分配内存,基本类型在栈中分配内存。
a)当需要往ArrayList,HashMap中放东西时,只能放包装类,因为容器都是装object的。
b)要调用Integer.toHexString();这样的方法时用到包装类,因为基本类型没有方法。
2、包装类与常量池
http://blog.csdn.net/olanlanxiari/article/details/8104505
Byte,Short,Integer,Long,Character,Boolean 这些包装类在 -128~127 的范围内实现了常量池。
Float、Double 则没有实现常量池。
//i1,i2 在堆中创建
Integer i1=new Integer(1);
Integer i2=new Integer(1);
System.out.println(i1==i2);//输出false
//i3,i4 指向常量池中同一个内存空间
Integer i3=1;
Integer i4=1;
System.out.println(i3==i4);//输出true
//很显然,i1,i3位于不同的内存空间
System.out.println(i1==i3);//输出false
//128在常量池中没有,在堆中new对象
Integer i3=128;
Integer i4=128;
System.out.println(i3==i4);//输出false
String 也实现了常量池
//s1,s2分别位于堆中不同空间
String s1=new String("hello");
String s2=new String("hello");
System.out.println(s1==s2)//输出false
//s3,s4位于池中同一空间
String s3="hello";
String s4="hello";
System.out.println(s3==s4);//输出true
实际上,在执行 String s1=new String(“hello”); 时创建了两个对象,一个放在常量池中,一个放在堆中,s1 是堆中的对象。
Java 反射
1、 Java 有多少种方式创建对象
使用New关键字、使用Class类的newInstance方法、使用Constructor类的newInstance方法、使用Clone方法、使用反序列化。