Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

Is it possible to find out if some a list is fixed size or not? I mean, for example this code:

String[] arr = {"a", "b"};
List<String> list = Arrays.asList(array);

returns fixed size List backed by an array. But is it possible to understand programmatically if List is fixed-size or not without trying to add/remove elements and catching the exception? For example:

try {
    list.add("c");
}
catch(UnsupportedOperationException e) {
    // Fixed-size?
}
like image 400
agurylev Avatar asked Sep 09 '25 20:09

agurylev


2 Answers

A list created from a String[] by

List<String> list = Arrays.asList(array);

will have Arrays as enclosing class, while one created by for example new ArrayList() won't have the enclosing class. So the following should work to check if the List was produced as a result of calling Arrays.toList():

static <T> boolean wasListProducedAsAResultOfCallingTheFunctionArrays_asList(List<T> l) {
    return Arrays.class.equals(l.getClass().getEnclosingClass());
}

Beware that this method relies on undocumented behavior. It will break if they added another nested List subclass to the Arrays class.

like image 122
baao Avatar answered Sep 12 '25 12:09

baao


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.

like image 20
Stephen C Avatar answered Sep 12 '25 10:09

Stephen C