Conceptually, I would prefer the @laune solution much more. I would prefer that the security type and compilation errors perforce throw a bunch of things into the list and forget to add the allowed type.
This, as they say, is still possible to do, although you have to do a bunch of unnecessary things to make it practical, that is, if you delete the type of an object, you must also delete all the objects that are associated with it, and other methods must be redefined e.g. addAll to provide proper functionality.
This approach makes it more flexible than laune, though, since you can add allowedTypes at any time. For your situation, probably not the best, but the general question is still intriguing enough that I took the picture. You may need some of your lists for storing integers, but not for others. You can do this with the addPermittedObject method.
public class SelectiveList extends ArrayList<Object> { //the (types of) objects that we can store private ArrayList<Object> permittedObjects = new ArrayList<Object>(); // put an Object type into the list public boolean addPermittedObject(Object o) { for (Object type : permittedObjects) { if (type.getClass() == o.getClass()) { return false; // if we already have it, do not add it again } } return permittedObjects.add(o); // else let add it } // remove the Object type public boolean removePermittedObject(Object o) { for (Object type : permittedObjects) { if (type.getClass() == o.getClass()) { return permittedObjects.remove(type); } } return false; } @Override public boolean add(Object o) { for (Object type : permittedObjects) { if (type.getClass() == o.getClass()) { return super.add(o); // go ahead and add the item since it // matches our list } } return false; } }
And check this out:
public static void main(String[] args) { SelectiveList selectiveList = new SelectiveList(); selectiveList.add("Potato"); selectiveList.add(1); selectiveList.add(true); System.out.println(selectiveList.size());
source share