2

So for school I am making a program where we are creating a booking system where people can book a ticket for a movie that has a capacity of 10 people. People are allowed to change the time of the booking to the next day as long as the theater is not full for that day.

An array will be no good in this situation as I need to be able to remove an object from the array and make another free space in said array, and then add the removed object to a different Array for the different day. This part is suitable for an ArrayList but it has no size limit so I'm stuck with what the best solution is. Any ideas that I can look into?

Thanks

2 Answers2

0

You can try the below, start from an array and convert it to list via Arrays.asList. Just note you could only use the set() method on the List, and not the add/remove methods as these would modify its size :

    String[] array = {"a1","b2","c3"};
    List<String> fixed = Arrays.asList(array);
    fixed.set(0, "new_string"); // OK
    fixed.add("aNewString"); // This will throw an exception
nullPointer
  • 4,419
  • 1
  • 15
  • 27
0

You can extend a class which already has the functionality you need and only override the methods required to implement new functionality (i.e. enforce a size limit). Consider the following solution:

public class CappedList<T extends Object> extends ArrayList<T> {

    private final int maxSize;

    public CappedList(int maxSize) {
        this.maxSize = maxSize;
    }

    @Override
    public boolean add(T e) {
        if (this.size() == this.maxSize) {
            //Already reached max size, abort adding
            throw new IllegalStateException("List is maxed out");
        } else {
            return super.add(e);
        }
    }

}

For completeness, you need to also override all add and addAll overloaded methods. You can then use this CappedList class instead of a simple ArrayList. A utility function isMaxedOut would be handy, in order to avoid exception handling:


public boolean isMaxedOut() {
        return this.size() == this.maxSize;
    }
Tasos P.
  • 3,994
  • 2
  • 21
  • 41