How to know if a List object has a fixed size

Java jansen :

How can I know if a List has a fixed size?

List<String> fixed = Arrays.asList(new String[100]);

This will create a fixed List. but the instantiated array of String object is not referenced to the String array anymore.

Ashvin solanki :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=110596&siteId=1