コード例 #1
0
ファイル: ArrayBag.java プロジェクト: schmidtg/classwork
  /**
   * containsAll - does this ArrayBag contain all of the items in otherBag? Returns false if
   * otherBag is null or empty.
   */
  public boolean containsAll(Bag otherBag) {
    if (otherBag == null || otherBag.numItems() == 0) return false;

    Object[] otherItems = otherBag.toArray();
    for (int i = 0; i < otherItems.length; i++) {
      if (!contains(otherItems[i])) return false;
    }

    return true;
  }
コード例 #2
0
ファイル: ArrayBag.java プロジェクト: schmidtg/classwork
  /**
   * 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;
  }