java simpleentry_Java java.util.AbstractMap.SimpleImmutableEntry的用法以及案例

1、SimpleEntry定义在抽象类AbstractMap里面,其构造方法与Pair类似。

2、AbstractMap类还包含一个嵌套类,表示不可变配对:SimpleImmutableEntry类。

实例代码:package com.what21;

import java.util.AbstractMap;

public class SimpleImmutableEntryMain {

/**

* @param args

*/

public static void main(String[] args) {

AbstractMap.SimpleEntry entry = new AbstractMap.SimpleEntry<>(1, "one");

entry.setValue("two");

Integer key = entry.getKey();

String value = entry.getValue();

System.out.println(key);

System.out.println(value);

AbstractMap.SimpleImmutableEntry entry2 = new AbstractMap.SimpleImmutableEntry<>(2, "two");

try {

entry2.setValue("three");

}catch(Exception e) {

e.printStackTrace();

// java.lang.UnsupportedOperationException

}

Integer key2 = entry2.getKey();

String value2 = entry2.getValue();

System.out.println(key2);

System.out.println(value2);

}

}

Java中的`java.util.concurrent.atomic.AtomicReference`提供了一种线程安全的方式来更新对象引用。它通过使用CAS(Compare-And-Swap)算法实现了原子性的操作。 下面是一个简单的案例,展示如何使用`AtomicReference`类: ```java import java.util.concurrent.atomic.AtomicReference; public class AtomicReferenceExample { public static void main(String[] args) { // 初始化AtomicReference对象 AtomicReference<String> atomicReference = new AtomicReference<>("Hello"); // 获取当前对象引用的值 String currentValue = atomicReference.get(); System.out.println("Current value: " + currentValue); // 比较并替换 boolean updated = atomicReference.compareAndSet("Hello", "World"); System.out.println("Value updated: " + updated); // 获取更新后的值 String updatedValue = atomicReference.get(); System.out.println("Updated value: " + updatedValue); } } ``` 在上面的示例中,我们首先创建了一个`AtomicReference`对象,并初始化为字符串`"Hello"`。然后我们使用`compareAndSet`方法比较当前对象引用的值是否为`"Hello"`,如果是,则将其替换为`"World"`。最后,我们获取更新后的值,并输出到控制台。 需要注意的是,`AtomicReference`类提供了许多其他有用的方法,如`set`、`getAndSet`、`weakCompareAndSet`等,可以根据具体的需求选择使用。 总之,`AtomicReference`类是Java中一种非常有用的线程安全对象引用类,可以避免多个线程同时修改对象引用时出现的竞争条件问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值