淺談java基本類型的封裝類型與對象池的概念

來源:互聯網
上載者:User
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介面,輕鬆序列化。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.