Java不可变对象如何回收,java之不可变对象一(immutable objects in java)

java之不可变对象1(immutable objects in java)

an immutable object

is an object

whose state cannot be modified after it is created.

不可变对象一旦被创建就它的状态就不能被修改。

A classic example of an immutable object is an instance of the Java String

class.

不可变对象的一个经典的例子是String类的实例。

String s = "ABC";

s.toLowerCase();

The method toLowerCase()

will not change the data "ABC" that s

contains.

Instead, a new String object is instantiated(被实例化

) and given the

data "abc" during its construction.

A reference to this String object is

returned by the toLowerCase()

method.

To make the String s

contain the data "abc", a different approach is needed.

s = s.toLowerCase();

Now the String s

references a new String object that

contains "abc". The String class's methods never affect the data that a

String object contains.

For an object to be immutable, there has to be no way to change

fields, mutable or not, and to access fields that are mutable.

Here is

an example of a mutable

object.

import java.util.ArrayList;

import java.util.LinkedList;

import java.util.List;

class Cart {

private final List items;

public Cart(List items) {

this.items = items;

}

public List getItems() {

return items;

}

public static void main(String[] args) {

List list = new ArrayList();

list.add("element1");

Cart cart = new Cart(list);

cart.getItems().add("element2");

// 下面的代码能运行吗?为什么

// list=new LinkedList();

// cart.items=list;

}

}

An instance of this class is not

immutable: one can add or remove items either by obtaining the field items

by calling getItems()

or by retaining(保留,保持

) a reference to the List object passed when an object of

this class is created.

The following change partially solves this

problem. In the ImmutableCart

class, the list is immutable:

you cannot add or remove items.

However, there is no guarantee that the

items are also immutable.

One solution is to use the decorator pattern

as a wrapper

around each of the list's items to make them also immutable.

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

class ImmutableCart {

private final List items;

public ImmutableCart(List items) {

this.items = Collections.unmodifiableList(new ArrayList(items));

}

public List getItems() {

return items;

}

public static void main(String[] args) {

List list = new ArrayList();

list.add("element1");

ImmutableCart cart = new ImmutableCart(list);

cart.getItems().add("element2");

}

}

运行抛出异常:

Exception in thread "main" java.lang.UnsupportedOperationException

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值