i want to limit the arraylist to 50. but i dont know how.
here's my code Object1.java
public class Object1 {
public String seat_no, id;
public Object1(String seat_no, String id) {
this.seat_no = seat_no;
this.id = id;
}
}
main.java
private ArrayList<Object1> list;
list = new ArrayList<Object1>();
As tempting as it may sound, I'd advise against extending ArrayList or any other List implementation, because then you'll be limiting yourself to using only one type of list. What happens if next time you want to limit a LinkedList and not an ArrayList? would you extend LinkedList too? what happens if you want to limit, basically, an arbitrary implementation of List?
What you're looking for already exists. You can use Commons Collections and wrap a list with a predicate:
class SizePredicate implements Predicate {
private List list;
private int maxSize;
public SizePredicate(List l, int size) {
list = l;
maxSize = size;
}
public boolean evaluate(Object obj) {
if (list.size() >= maxSize) {
throw new IllegalStateException("Your message here");
}
list.add(obj);
}
}
...
List list = new LinkedList(); // Or, really, any implementation of list.
List maxList = ListUtils.predicatedList(list, new SizePredicate(list, 50));
Using the design above, you can use the same Predicate instance to limit any sort of list. You can also extend it to handle any sort of collection...
... Without the need to extend any JDK class.
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