在 Java 中的 arrayList 中增加整数的最佳方法 [英] Best way to increment Integer in arrayList in Java

查看:113
本文介绍了在 Java 中的 arrayList 中增加整数的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 ArrayList 中增加整数的最简洁方法是什么?

What is the cleanest way to increment an Integer in an ArrayList?

ArrayList<Integer> ints = new ArrayList<>();
ints.add(5);
ints.add(9);

增加最后一个元素的最干净的方法是什么?

What is the cleanest way to increment the last element?

ints.set(ints.size() - 1, ints.get(ints.size() - 1) + 1); 对我来说看起来很丑.

ints.set(ints.size() - 1, ints.get(ints.size() - 1) + 1); seems pretty ugly to me.

推荐答案

也许你需要使用另一种数据结构?

Maybe you need to use another structure of data?

LinkedList<AtomicInteger> ints = new LinkedList<AtomicInteger>();
ints.add(new AtomicInteger(5));
ints.add(new AtomicInteger(9));

ints.getLast().incrementAndGet();

这篇关于在 Java 中的 arrayList 中增加整数的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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