1.问题
面试的时候经常会被问到String类对象在java中存放于(=@__@=)哪里以及string = "abc"与string = new String('abc')的区别,不知道你是否遇见了其很多次- -?比如说我面的去哪儿面试等。
2.概念
在JDK 5.0之后,java为了避免频繁的创建和销毁对象而影响性能(原因),设计了对于8种基本类型(6中number类型+char类型+布尔类型)+String类型的
共计 9 种类的对象池。
3.特性
(1)对象创建于对象池中,而对象池则位于方法区中的常量池。
定制对象池,参考http://blog.sina.com.cn/s/blog_6ede15b10100nfl4.html
import java.util.HashSet;
class Student {
private String name;
private int age;
private static HashSet<Student> pool = new HashSet<Student>();// 对象池
public Student(String name, int age) {
this.name = name;
this.age = age;
}
// 使用对象池来得到对象的方法
public static Student newInstance(String name, int age) {
// 循环遍历对象池
for (Student stu : pool) {
if (stu.name.equals(name) && stu.age == age) {
return stu;
}
}
// 如果找不到值相同的Student对象,则创建一个Student对象
// 并把它加到对象池中然后返回该对象。
Student stu = new Student(name, age);
pool.add(stu);
return stu;
}
}
public class MyPool {
public static void main(String[] args) {
Student stu1 = Student.newInstance("zhangsan", 30);// 对象池中拿
Student stu2 = Student.newInstance("zhangsan", 30);// 所以stu1==stu2
Student stu3 = new Student("zhangsan", 30);// 重新创建,所以stu1!=stu3
System.out.println(stu1 == stu2);
System.out.println(stu1 == stu3);
}
}
(2) 不可改变性。看如下例子:
<span style="white-space:pre"> </span>public class Snippet {
<span style="white-space:pre"> </span>public static void main(String []args){
<span style="white-space:pre"> </span>Byte c = (byte) 128;
<span style="white-space:pre"> </span>Byte c1 = (byte)128;
<span style="white-space:pre"> </span>System.out.println(c==c1);
<span style="white-space:pre"> </span>c1 = (byte)127;
<span style="white-space:pre"> </span>System.out.println(c==c1);
<span style="white-space:pre"> </span>Integer a = 5;
<span style="white-space:pre"> </span>Integer b = 5;
<span style="white-space:pre"> </span>System.out.println(a==b);
<span style="white-space:pre"> </span>a = 6;
<span style="white-space:pre"> </span>System.out.println(a==b);
}
}
当值相同时候,引用指向同一对象,当值不相同时候,引用就指向不相同对象了
(3)都实现了java.io.Serializable接口,轻松序列化。