Java中的可变布尔字段 [英] Mutable boolean field in Java

查看:570
本文介绍了Java中的可变布尔字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中需要一个可变的布尔字段(稍后我将通过get *方法返回此字段,并且应该可以修改此字段)。

I need a mutable boolean field in Java (I will return this field via get* method later and it should be possible to modify this field).

布尔值不行,因为布尔类中没有set *方法(我会说布尔值是不可变的,你只能改变引用,但你不能改变对象本身)。

Boolean doesn't work because there are no set* methods in the Boolean class (I would say that Boolean is immutable, you can only change the reference, but you can't change the object itself).

我想我可以使用大小为1的布尔数组。但是可能有更优雅的解决方案?

I guess I can use Boolean array of size 1. But probably there are more elegant solutions?

为什么Java没有这么简单的东西? ?

Why doesn't Java have such a simple thing?

推荐答案

不可变类更易于使用。它们永远不会改变,并发代码也不会出现问题。 (基本上,打破它们的可能性较小。)

Immutable classes are easier to work with. They'll never change and there will be no problems with concurrent code. (Basically, there are fewer possibilities to break them.)

如果要返回对布尔值的引用,可以使用 java .util.concurrent.atomic.AtomicBoolean 如果你使用多线程或工作老式 org.apache.commons.lang.mutable.MutableBoolean

If you would like to return a reference to your Boolean value, you can use java.util.concurrent.atomic.AtomicBoolean if you're working with multiple threads or plain old org.apache.commons.lang.mutable.MutableBoolean.

这篇关于Java中的可变布尔字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆