List<String> strList = new ArrayList<String>()
List<Integer> intList = new ArrayList<Integer>()
If a collection refuses to add a particular element for any reason other than that it already contains the element, it must throw an exception (rather than returning false).
@throws ClassCastException if the class of the specified element prevents it from being added to this collection
If you want/need to deviate from that, you should clearly document it.
I still don't see why you'd want or need something like this, though. Could you elaborate some more about how you intend to use such an implementation?
Jeremy Watts wrote:Yes sorry, should have been more specific. What I want is for, during runtime, for either Integers, or Strings, only to be 'addable' to the list - but if an attempt were made to add a String to an already created List of Integers, then an error be thrown, and vice versa.
But isn't that what you already get at compile time when you declare an ArrayList of type String or Integer?
I have an ArrayList, defined as:-
ArrayList<Item> factors = new ArrayList<Item>();
Where, 'Item' is an inner class, defined as :-
public static class Item implements Comparable<Item>
private int factorPower;
private UnivariatePolynomial factor;
public Item(UnivariatePolynomial factor, int factorPower)
this.factor = factor;
this.factorPower = factorPower;
And here, 'UnivariatePolynomial' is an abstract class that has two classes that extend it. These are:-
'UPOverFiniteField', and 'UPOverZ'.
So, what I'm trying to do is to allow a list of one 'type' of item only, but to throw an error if one type is added to a list of the other.
So, the only way that remains is checking it at runtime - do a check whenever an element is added to the list, and if it isn't the expected type, throw an exception.
*edit* - Here's an idea; you could make class Item generic. Like this:
Then you can create a list like this: