在 Java 中定义一个固定大小的列表 [英] Define a fixed-size list in Java

查看:94
本文介绍了在 Java 中定义一个固定大小的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以定义一个固定大小为 100 的列表?如果不是,为什么这在 Java 中不可用?

Is it possible to define a list with a fixed size that's 100? If not why isn't this available in Java?

推荐答案

,

Commons 库 提供了一个内置的 FixedSizeList 不支持 addremoveclear 方法(但 set 方法是允许的,因为它不会修改 List 的大小).换句话说,如果您尝试调用这些方法之一,您的列表仍然保持相同的大小.

Commons library provides a built-in FixedSizeList which does not support the add, remove and clear methods (but the set method is allowed because it does not modify the List's size). In other words, if you try to call one of these methods, your list still retain the same size.

要创建固定大小的列表,只需调用

To create your fixed size list, just call

List<YourType> fixed = FixedSizeList.decorate(Arrays.asList(new YourType[100]));

<小时>

您可以使用 unmodifiableList 如果您想要指定列表的不可修改视图,或对内部列表的只读访问.

List<YourType> unmodifiable = java.util.Collections.unmodifiableList(internalList);

这篇关于在 Java 中定义一个固定大小的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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