-1

How do I make an ArrayList not exceed a size of 3, as shown here:

ArrayList <Integer> list = new ArrayList<Integer>(3);

Is there a certain method that will ensure the ArrayList does not grow past 3 entries?

I tried ensureCapacity(), trimToSize(), but they do not do what I want

  • 2
    At this point you might as well just use an array then. Arrays do not grow. – Sweeper May 03 '23 at 02:21
  • I want to use the ArrayList's prebuilt methods and an array will not work for my case – CrustyCrustecean May 03 '23 at 02:27
  • I suppose you could extend ArrayList and override the methods that add and replace elements. – Jeff Holt May 03 '23 at 02:27
  • this means I have to create my own methods. I am asking if there is anything available already that would prevent this – CrustyCrustecean May 03 '23 at 02:28
  • No, there's no Class that I know of that would put an artificial limit on cardinality. – Jeff Holt May 03 '23 at 02:29
  • @CrustyCrustecean you can use an array or implement custom a List for that – Ngo Tuoc May 03 '23 at 02:39
  • Does it have to be `java.util.ArrayList` specifically? Or are you ok with just `java.util.List`? Because if you are ok with that, then there are a couple of solutions available to you. – davidalayachew May 03 '23 at 03:19
  • 1
    Otherwise, like the other commenters have said, the entire point of `java.util.ArrayList` was to make it easily resizable. It does not have the ability to turn that off. That would defeat the entire purpose of having an `ArrayList` at all. At that point, you would either use an array or an unmodifiable `List`. – davidalayachew May 03 '23 at 03:20
  • I want to be able to use `contains()` of the ArrayList class on a simple array. Is there such a thing. I don't want to use ArrayList cause it won't stop growing – CrustyCrustecean May 03 '23 at 03:30
  • Nobody has mentioned this yet ... but the *capacity* of an `ArrayList` is not the same as its *size*. They are different concepts. For example, `new ArrayList<>(3)` creates a list whose initial size is `0` ... as returned by the `size()` method. – Stephen C May 03 '23 at 10:52

1 Answers1

0

Java doesn't offer something like that. Maybe Collections.unmodifiableList could be something close, but it doesn't let you add, update or remove elements, just read the values from an already initialized list.

You have FixedSizeList from Apache commons collections. You can only set values in specific positions, but you can't add or remove them

Gastón Schabas
  • 2,153
  • 1
  • 10
  • 17