Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a fixed size "list" in Java?

Since the Java core library doesn't have such a collection, would an array be the best option, especially if one doesn't want to rely on third-party libraries?

like image 317
mre Avatar asked Jan 23 '12 17:01

mre


People also ask

How do you create a fixed size array in Java?

Array Initialization in Java To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size: int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable.

Can we set the size of list in Java?

To create an ArrayList of specific size, you can pass the size as argument to ArrayList constructor while creating the new ArrayList. Following the syntax to create an ArrayList with specific size. myList = new ArrayList<T>(N);

What is a fixed size list?

A collection with a fixed size is simply a collection with a wrapper that prevents adding and removing elements; therefore, if changes are made to the underlying collection, including the addition or removal of elements, the fixed-size collection reflects those changes. This method is an O(1) operation.

Is ArrayList fixed size in Java?

ArrayList's size and capacity are not fixed. The logical size of the list changes based on the insertion and removal of elements in it. This is managed separately from its physical storage size.


1 Answers

Arrays.asList(T ...) Returns a fixed-size list backed by the specified array

Object[] array = new Object[10];
List<Object> fixedList = Arrays.asList(array);
like image 108
Aviram Segal Avatar answered Sep 20 '22 06:09

Aviram Segal