Define a Fixed-Size List in Java

Define a fixed-size list in Java

FixedSizeList

Yes,

The Apache Commons library provides the FixedSizeList class 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). Ditto for FixedSizeList in Eclipse Collections. If you try to call one of these methods, your list remains the same size.

To create your fixed size list, just call

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

You can use unmodifiableList if you want an unmodifiable view of the specified list, or read-only access to internal lists.

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

Initial size for the ArrayList

You're confusing the size of the array list with its capacity:

  • the size is the number of elements in the list;
  • the capacity is how many elements the list can potentially accommodate without reallocating its internal structures.

When you call new ArrayList<Integer>(10), you are setting the list's initial capacity, not its size. In other words, when constructed in this manner, the array list starts its life empty.

One way to add ten elements to the array list is by using a loop:

for (int i = 0; i < 10; i++) {
arr.add(0);
}

Having done this, you can now modify elements at indices 0..9.

How to implement a fixed size list in Java?

I'd write a wrapper class around an ArrayList, and in the add and addAll methods, I'd check for the list's size before adding new elements. If you have reached the maximum size, you can then throw an exception (or do nothing, depending on what you really want to do in your code).

Here's a short example:

public class SizeLimitedArray<E> implements java.util.List<E>
{
private static final int DEFAULT_SIZE_LIMIT = 10;
private ArrayList<E> myList;
private int maxSize;

public SizeLimitedArray ()
{
this (DEFAULT_SIZE_LIMIT);
}

public SizeLimitedArray (int size)
{
myList = new ArrayList<E> (size);
maxSize = size;
}

@Override
public boolean add (E objectToAdd)
{
if (myList.size () > maxSize)
{
throw new IllegalStateException ("The array is full");
}

return myList.add (objectToAdd);
}

@Override
public boolean addAll (Collection collectionToAdd)
{
if (myList.size () + collectionToAdd.size () > maxSize)
{
throw new IllegalStateException ("The array is full");
}

return myList.addAll (collectionToAdd);
}

// Rest of class omitted for brevity
}

From ArrayListArrayListObject to fixed size array/list

You can use Arrays.asList() to created fixed sized Lists.

Examples:

A List of size 3, initialized with null values:

List<ArrayList<Object>> models = Arrays.asList (null,null,null);

A List of size 3, initialized with non-null values:

List<ArrayList<Object>> models = Arrays.asList (new ArrayList<Object> (),new ArrayList<Object> (),new ArrayList<Object> ());

A List of size 10, initialized with null values:

List<ArrayList<Object>> models = Arrays.asList ((ArrayList<Object>[])new ArrayList[10]);

Note that add operation is not supported for fixed sized lists. You'll have to use models.set(index,new ArrayList<Object>()) instead.

EDIT:

Here's another way to initialize the List using Streams:

List<ArrayList<Object>> models = Arrays.asList (Stream.generate (ArrayList::new).limit (10).toArray (ArrayList[]::new));

Java: How to initialize a fixed length List of List?

If you want your lists to be absolutely fixed size, you could use the native arrays. They can be multi-dimensional so for example you can have String[][] x or `String[][][] y'.

Honestly however, your approach is a bit confusing and not that crisp from a design point of view.

Why not, similarly to as was suggested in the comment, have an object which has both columns (xColumn1, xColumn2), and then have the Y elements in a separate object, which can then be associated with the first one?

so:

class XDetails
{
String xColumn1;
String xColumn2;

YDetails relatedY;
...
}

class YDetails
{
... fields of Y ...

}

Then you can have an array or List<XDetails>

Why does Arrays.asList return a fixed-size List?

The point is that Arrays.asList is returning a view of the array, and that changes to the array are reflected in the List and vice versa. It's not making a copy, it's just a very simple implementation of the List interface that interprets the specified array as a List. As a result, Arrays.asList is really just reflecting that Java arrays are fixed-size, too. You can't add or remove elements from the backing array, either.

As mentioned in the comments, it's quite easy to get a variable-size list from an array with e.g. new ArrayList<>(Arrays.asList(array)).

Also, for what it's worth: Guava actually regrets providing a "resizable list from varargs arguments" method after discovering that most people who used it actually really wanted an immutable list.

How to make a new List in Java

List myList = new ArrayList();

or with generics (Java 7 or later)

List<MyType> myList = new ArrayList<>();

or with generics (Old java versions)

List<MyType> myList = new ArrayList<MyType>();

How to know if a List object has a fixed size

Ref: Is it possible to find out if some list is fixed size or not?

Is it possible to find out if some list is fixed size or not?

In theory - No. Fixed sizedness is an emergent property of the implementation of a list class. You can only determine if a list has that property by trying to add an element.

And note that a simple behavioral test would not reliably distinguish between a fixed sized list and a bounded list or a list that was permanently or temporarily read-only.

In practice, a fixed sized list will typically have a different class to an ordinary one. You can test the class of an object to see if it or isn't a specific class. So if you understand what classes would be used to implement fixed sized lists in your code-base, then you can test if a specific list is fixed sized.

For example the Arrays.asList(...) method returns a List object whose actual class is java.util.Arrays.ArrayList. That is a private nested class, but you could use reflection find it, and then use Object.getClass().equals(...) to test for it.

However, this approach is fragile. Your code could break if the implementation of Arrays was modified, or if you started using other forms of fixed sized list as well.



Related Topics



Leave a reply



Submit