Is it possible to define a list with a fixed size that's 100? If not why isn't this available in Java?
The java. util. ArrayList. size() method returns the number of elements in this list i.e the size of the list.
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);
ArrayList's size and capacity are not fixed. This is managed separately from its physical storage size.
The size() method of the List interface in Java is used to get the number of elements in this list. That is, this method returns the count of elements present in this list container. Parameters: This method does not take any parameters. Return Value: This method returns the number of elements in this list.
This should do it if memory serves:
List<MyType> fixed = Arrays.asList(new MyType[100]);
A Java list is a collection of objects ... the elements of a list. The size of the list is the number of elements in that list. If you want that size to be fixed, that means that you cannot either add or remove elements, because adding or removing elements would violate your "fixed size" constraint.
The simplest way to implement a "fixed sized" list (if that is really what you want!) is to put the elements into an array and then Arrays.asList(array)
to create the list wrapper. The wrapper will allow you to do operations like get
and set
, but the add
and remove
operations will throw exceptions.
And if you want to create a fixed-sized wrapper for an existing list, then you could use the Apache commons FixedSizeList
class. But note that this wrapper can't stop something else changing the size of the original list, and if that happens the wrapped list will presumably reflect those changes.
On the other hand, if you really want a list type with a fixed limit (or limits) on its size, then you'll need to create your own List class to implement this. For example, you could create a wrapper class that implements the relevant checks in the various add
/ addAll
and remove
/ removeAll
/ retainAll
operations. (And in the iterator remove
methods if they are supported.)
So why doesn't the Java Collections framework implement these? Here's why I think so:
Collections.sort
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With