To avoid adding elements to an ArrayList
in Java once a specified limit is reached, you can create a custom class that
wraps around ArrayList and
enforces the size limit. This custom class will control the behavior of the ArrayList
by preventing the addition of new elements beyond the specified limit.
Here's a step-by-step guide to implement such a custom class:
1. Define the Custom Class
Create a custom class that encapsulates an ArrayList
and includes logic to enforce the size limit.
2. Implement Methods to Control
Access
Override methods related to adding elements to ensure that the limit is
enforced.
Example Implementation
Here’s a sample implementation of a custom LimitedArrayList
class:
public class LimitedArrayList<E> { private final List<E> list; private final int limit; public LimitedArrayList(int limit) { this.list = new ArrayList<>(); this.limit = limit; } // Add an element to the list if the size is within the limit public boolean add(E element) { if (list.size() >= limit) { throw new IllegalStateException("Cannot add more elements: limit reached"); } return list.add(element); } // Add all elements from a collection if it does not exceed the limit public boolean addAll(Collection<? extends E> c) { if (list.size() + c.size() > limit) { throw new IllegalStateException("Cannot add elements: limit would be exceeded"); } return list.addAll(c); } }
Usage Example
Here’s how you can use the LimitedArrayList
class:
public class Main { public static void main(String[] args) { // Create a LimitedArrayList with a limit of 5 elements LimitedArrayList<String> limitedList = new LimitedArrayList<>(5); // Add elements to the list try { for (int i = 1; i <= 6; i++) { limitedList.add("Element " + i); System.out.println("Added: Element " + i); } } catch (IllegalStateException e) { System.out.println(e.getMessage()); // Outputs: Cannot add more elements: limit reached } // Print the final list System.out.println("Final List: " + limitedList); }}
No comments:
Post a Comment