/** Increase capacity of current object */ public void increaseCapacity(int increment) { if (increment < 0) throw new IllegalArgumentException("Must increase capacity by number greater than 0."); else if (increment == 0) return; else { // Determine new objects capacity int newCapacity = this.capacity() + increment; // Create a new ArrayBag with current size + increment ArrayBag b = new ArrayBag(newCapacity); // Add contents of current ArrayBag to new ArrayBag Object[] current = this.toArray(); for (int i = 0; i < current.length; i++) { b.add(current[i]); } // Reset references for private fields of 'this' this.items = b.items; this.numItems = b.numItems; } }
/** * unionWith * * <p>Return a non-duplicate ArrayBag as the union of the incoming and calling object */ public Bag unionWith(Bag other) { // Check if either bag is empty if (this.numItems() == 0 && other.numItems() == 0) { return new ArrayBag(); } // Determine the size of the new ArrayBag int newCapacity = this.capacity() + other.capacity(); // Create new ArrayBag to hold unioned values ArrayBag b = new ArrayBag(newCapacity); // Convert the incoming object to an array and copy each of its items // that are not in the new ArrayBag Object[] other_arr = other.toArray(); Object[] this_arr = this.toArray(); // Determine which ArrayBag has more items int loop_count = ((other_arr.length > this_arr.length) ? other_arr.length : this_arr.length); for (int i = 0; i < loop_count; i++) { // Add 'this' item if it doesn't exist and will not IndexOutOfBounds if (i < this_arr.length) { if (!b.contains(this_arr[i])) { b.add(this_arr[i]); } } // Add 'other's item if it doesn't exist and will not IndexOutOfBounds if (i < other_arr.length) { if (!b.contains(other_arr[i])) { b.add(other_arr[i]); } } } return b; }
@Test public void instantiation() { ArrayBag<String> bagOfStrings = new ArrayBag<String>(); ArrayBag<Integer> bagOfIntegers = new ArrayBag<Integer>(); bagOfStrings.add("Thunder"); bagOfIntegers.add(42); assertEquals(1, bagOfStrings.size()); assertEquals(1, bagOfIntegers.size()); }
@Test public void testArrayBag() { ArrayBag<Integer> bag = new ArrayBag<Integer>(); // a one-item bag bag.add(1); assertEquals(1, bag.size()); Iterator<Integer> it = bag.iterator(); assertTrue(it.hasNext()); int j = it.next(); assertEquals(1, j); assertFalse(it.hasNext()); it.remove(); assertEquals(0, bag.size()); assertFalse(it.hasNext()); // a two-item bag bag.add(1); bag.add(2); assertEquals(2, bag.size()); it = bag.iterator(); assertTrue(it.hasNext()); j = it.next(); assertEquals(1, j); assertTrue(it.hasNext()); // test removal; this should not break iteration it.remove(); assertEquals(1, bag.size()); assertTrue(it.hasNext()); j = it.next(); assertEquals(2, j); assertFalse(it.hasNext()); bag = new ArrayBag<Integer>(); bag.add(1); bag.add(2); bag.add(3); it = bag.iterator(); assertTrue(it.hasNext()); j = it.next(); j = it.next(); it.remove(); j = it.next(); assertEquals(3, j); it.remove(); assertFalse(it.hasNext()); }