Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an ArrayList that can store 50 strings in Java?

Tags:

java

arraylist

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>();
like image 414
oyan11 Avatar asked Feb 21 '26 02:02

oyan11


1 Answers

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.

like image 56
Isaac Avatar answered Feb 22 '26 14:02

Isaac