diff --git a/src/java/org/apache/commons/collections/TreeBag.java b/src/java/org/apache/commons/collections/TreeBag.java index 098d51bd7..f591eb2db 100644 --- a/src/java/org/apache/commons/collections/TreeBag.java +++ b/src/java/org/apache/commons/collections/TreeBag.java @@ -62,6 +62,14 @@ public class TreeBag extends DefaultMapBag implements SortedBag { addAll(coll); } + public boolean add(Object o) { + if(comparator() == null && !(o instanceof Comparable)) { + throw new IllegalArgumentException("Objects of type " + o.getClass() + " cannot be added to " + + "a naturally ordered TreeBag as it does not implement Comparable"); + } + return super.add(o); + } + public Object first() { return ((SortedMap) getMap()).firstKey(); } diff --git a/src/java/org/apache/commons/collections/bag/TreeBag.java b/src/java/org/apache/commons/collections/bag/TreeBag.java index 6c4ca968d..7191d6d3e 100644 --- a/src/java/org/apache/commons/collections/bag/TreeBag.java +++ b/src/java/org/apache/commons/collections/bag/TreeBag.java @@ -80,6 +80,15 @@ public class TreeBag addAll(coll); } + //----------------------------------------------------------------------- + public boolean add(Object o) { + if(comparator() == null && !(o instanceof Comparable)) { + throw new IllegalArgumentException("Objects of type " + o.getClass() + " cannot be added to " + + "a naturally ordered TreeBag as it does not implement Comparable"); + } + return super.add(o); + } + //----------------------------------------------------------------------- public Object first() { return ((SortedMap) getMap()).firstKey(); diff --git a/src/test/org/apache/commons/collections/TestTreeBag.java b/src/test/org/apache/commons/collections/TestTreeBag.java index 59d83fb70..5dcd5e60d 100644 --- a/src/test/org/apache/commons/collections/TestTreeBag.java +++ b/src/test/org/apache/commons/collections/TestTreeBag.java @@ -70,4 +70,15 @@ public class TestTreeBag extends AbstractTestBag { assertEquals("Should get last key", "D", ((SortedBag)bag).last()); } + + public void testCollections265() { + Bag bag = new TreeBag(); + try { + bag.add(new Object()); + fail("IllegalArgumentException expected"); + } catch(IllegalArgumentException iae) { + // expected; + } + } + } diff --git a/src/test/org/apache/commons/collections/bag/TestTreeBag.java b/src/test/org/apache/commons/collections/bag/TestTreeBag.java index 6a9e04290..7df16dc2e 100644 --- a/src/test/org/apache/commons/collections/bag/TestTreeBag.java +++ b/src/test/org/apache/commons/collections/bag/TestTreeBag.java @@ -71,6 +71,16 @@ public class TestTreeBag extends AbstractTestBag { assertEquals("Should get last key", "D", ((SortedBag)bag).last()); } + + public void testCollections265() { + Bag bag = new TreeBag(); + try { + bag.add(new Object()); + fail("IllegalArgumentException expected"); + } catch(IllegalArgumentException iae) { + // expected; + } + } public String getCompatibilityVersion() { return "3";