浅谈java基本类型的封装类型与对象池的概念

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接口,轻松序列化。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值