3

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.

Java jansen
  • 187
  • 2
  • 15

2 Answers2

2

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.

Ashvin solanki
  • 4,802
  • 3
  • 25
  • 65
-5

you can use Set,Set can enter unlimited object

  • This does not answer the question, nor is it an answer at all. It would be a comment. Please wait until you have enough reputation to give [comments](https://stackoverflow.com/help/privileges/comment). – LuCio Sep 27 '18 at 07:36
  • it's also not correct. a Set can contain a lot of objects, but it's limited by the resources of the environment, and by the implementation of Java itself. same goes for a List, btw – Stultuske Sep 27 '18 at 07:39