Question

This wont take you more than 15 mins. Comple the two method and besure to test...

This wont take you more than 15 mins.

Comple the two method and besure to test with Junit test that provided below.

toArray() -- this method returns a newly allocated array containing the elements in the multiset. The array this method returns must only contain the elements in the multiset and not any nulls or other values that are stored in the backing store, but are not in the multiset.

fromArray(E[] arr) -- this method updates the multiset so that it contains the data in arr. Check if arr is larger than the backing store and, if it is, allocate a new array to be used by the backing store. You should then set the size of the multiset equal to the length of arr and assign those entries in the backing store from the entries in arr.

------------------------------------------

package edu.buffalo.cse116;

import java.util.Collection;
import java.util.Iterator;

/**
 * Class which implements the concept of a multiset -- an unorganized collection which does not limited the number of
 * times an instance can be added.
 *
 * @author Carl Alphonse
 * @author Matthew Hertz
 * @param  Type of data contained with the instance.
 */
public class ArrayMultiSet implements Collection {
  /** Unless otherwise specified, the default length to which the backing store should be initialized. */
  private static final int DEFAULT_INITIAL_CAPACITY = 16;

  /** Array in which the elements in this multiset are stored. */
  private E[] _store;
  /**
   * Array indices below this amount contain the active elements in this collection.
   */
  private int _size;

  /**
   * Create a new empty multiset.
   */
  public ArrayMultiSet() {
    clear();
  }

  /**
   * Remove all of the elements within the instance and invalidate any current iterators.
   */
  @SuppressWarnings("unchecked")
  @Override
  public void clear() {
    _store = (E[]) (new Object[DEFAULT_INITIAL_CAPACITY]);
    _size = 0;
  }

  @Override
  public int size() {
    return _size;
  }

  @Override
  public boolean isEmpty() {
    return _size == 0;
  }

  /**
   * Returns a newly allocated array containing the elements in the Multiset. The length of returned array will be the
   * current size of the Multiset with no padding or extra spaces added.
   *
   * @return Newly allocated array whose entries are set to the elements in the Multiset.
   */
  @Override
  public Object[] toArray() {

  }

  /**
   * Resets the Multiset so that it only contains the entries in the given array. This overwrites the data previously in
   * the Collection.
   *
   * @param arr The array whose entries will be the elements in the Collection
   */
  @SuppressWarnings("unchecked")
  public void fromArray(E[] arr) {
    // IMPORTANT: You CANNOT set the backing store to be equal to ("alias")
    // arr. If you did this, the calling method could make changes to the
    // Multiset by updating the entries in arr rather than using the Multiset methods.
    // This violates good OO practice and creates the potential for bugs and hacks.
  }

  /**
   * Update the multiset so that it includes all of the elements from before the call AND the given element.
   *
   * @param e Item to be added to this collection.
   */
  @Override
  public boolean add(E e) {
    // To be discussed on Friday!
    throw new UnsupportedOperationException();
  }

  /**
   * Removes a single instance of the given object, if one can be found in the multiset. The method returns {@code true}
   * if a match was found (and removed) and {@code false} if no match was found. Normally, this uses
   * {@link Object#equals} to check if there is a match, but uses {@code ==} when {@code obj} is {@code null}.
   *
   * @param obj Object (or null) which we want to remove
   * @return {@code true} if {@code obj} was found and an instance removed; {@code false} if a match could not be found.
   */
  @Override
  public boolean remove(Object obj) {
    // To be discussed Monday!
    throw new UnsupportedOperationException();
  }

  /**
   * Return true if at least one element in the multiset is equal to the given object. When {@code obj} is null, it must
   * use the {@code ==} operator to perform these checks, but when {@code obj} is not null, the {@link Object#equals}
   * method is used.
   *
   * @param obj Object (or null) for which we will search
   * @return {@code true} if {@code obj} was found and an instance removed; {@code false} if a match could not be found.
   */
  @Override
  public boolean contains(Object obj) {
    // To be discussed Monday!
    throw new UnsupportedOperationException();
  }

  /*
   * The remaining methods are part of the Collection interface, but are beyond what is necessary for CSE 116.
   * Students who want a complete Multiset implementation should investigate Google's "Guava" library.
   */
  @Override
  public Iterator iterator() {
    throw new UnsupportedOperationException();
  }

  @Override
  public  T[] toArray(T[] a) {
    throw new UnsupportedOperationException();
  }

  @Override
  public boolean containsAll(Collection c) {
    throw new UnsupportedOperationException();
  }

  @Override
  public boolean addAll(Collection c) {
    throw new UnsupportedOperationException();
  }

  @Override
  public boolean removeAll(Collection c) {
    throw new UnsupportedOperationException();
  }

  @Override
  public boolean retainAll(Collection c) {
    throw new UnsupportedOperationException();
  }
}

-------------------------

Junit test part

private ArrayMultiSet testeeInt;
private ArrayMultiSet testeeString;

@Test
public final void testFromArrayLength0() throws Exception {
String[] emptyArray = new String[0];
Object[] storeArr = getStore(testeeString);
testeeString.fromArray(emptyArray);
int _size = getSize(testeeString);
assertEquals("_size should be set to arr's length in fromArray()", 0, _size);
Object[] newStore = getStore(testeeString);
assertSame("fromArray() should not allocate a new array for _store unless _store is smaller than arr", storeArr,
newStore);
}

@Test
public final void testFromArrayLengthSmaller() throws Exception {
Integer[] mediumArray = new Integer[15];
Integer[] refArray = new Integer[15];
Random rnd = new Random();
for (int i = 0; i < mediumArray.length; i++ ) {
mediumArray[i] = rnd.nextInt();
refArray[i] = mediumArray[i];
}
Object[] storeArr = getStore(testeeInt);
testeeInt.fromArray(mediumArray);
int _size = getSize(testeeInt);
assertEquals("_size should be set to arr's lengt in fromArray()", 15, _size);
Object[] newStore = getStore(testeeInt);
assertSame("fromArray() should not allocate a new array for _store unless _store is smaller than arr!", storeArr,
newStore);
for (int i = 0; i < refArray.length; i++ ) {
assertSame("fromArray() should have assigned the entries in _store to equal the entries in arr. At index " + i,
refArray[i], newStore[i]);
}
}

@Test
public final void testFromArrayLengthEqual() throws Exception {
Integer[] mediumArray = new Integer[16];
Integer[] refArray = new Integer[16];
Random rnd = new Random();
for (int i = 0; i < mediumArray.length; i++ ) {
mediumArray[i] = rnd.nextInt();
refArray[i] = mediumArray[i];
}
Object[] storeArr = getStore(testeeInt);
testeeInt.fromArray(mediumArray);
int _size = getSize(testeeInt);
assertEquals("_size should be set to arr's lengt in fromArray()", 16, _size);
Object[] newStore = getStore(testeeInt);
assertSame("fromArray() should not allocate a new array for _store unless _store is smaller than arr!", storeArr,
newStore);
for (int i = 0; i < refArray.length; i++ ) {
assertSame("fromArray() should have assigned the entries in _store to equal the entries in arr. At index " + i,
refArray[i], newStore[i]);
}
}

@Test
public final void testFromArrayLengthSlightlyLarger() throws Exception {
String[] mediumArray = new String[17];
String[] refArray = new String[mediumArray.length];
Random rnd = new Random();
for (int i = 0; i < mediumArray.length; i++ ) {
mediumArray[i] = Integer.toHexString(rnd.nextInt());
refArray[i] = mediumArray[i];
}
testeeString.fromArray(mediumArray);
int _size = getSize(testeeString);
assertEquals("_size should be set to arr's lengt in fromArray()", 17, _size);
Object[] newStore = getStore(testeeString);
assertNotSame("fromArray() must allocate a new array for _store when arr's length is greater than _store's length. It cannot just set _store equal to arr",
mediumArray, newStore);
assertTrue("_store length must be at least as large as the size()", mediumArray.length <= newStore.length);
for (int i = 0; i < refArray.length; i++ ) {
assertSame("fromArray() should have assigned the entries in _store to equal the entries in arr. At index " + i,
refArray[i], newStore[i]);
}
}

@Test
public final void testFromArrayLengthMuchLarger() throws Exception {
Integer[] mediumArray = new Integer[45];
Integer[] refArray = new Integer[mediumArray.length];
Random rnd = new Random();
for (int i = 0; i < mediumArray.length; i++ ) {
mediumArray[i] = rnd.nextInt();
refArray[i] = mediumArray[i];
}
testeeInt.fromArray(mediumArray);
int _size = getSize(testeeInt);
assertEquals("_size should be set to arr's length in fromArray()", 45, _size);
Object[] newStore = getStore(testeeInt);
assertNotSame("fromArray() must allocate a new array for _store when arr's length is greater than _store's length. It cannot just set _store equal to arr",
mediumArray, newStore);
assertTrue("_store length must be at least as large as the size()", mediumArray.length <= newStore.length);
for (int i = 0; i < refArray.length; i++ ) {
assertSame("fromArray() should have assigned the entries in _store to equal the entries in arr. At index " + i,
refArray[i], newStore[i]);
}
}

@Test
public final void testFromArrayOverwriteData() throws Exception {
String[] initArray = new String[64];
Random rnd = new Random();
for (int i = 0; i < 35; i++ ) {
initArray[i] = Integer.toHexString(rnd.nextInt(67));
}
setSize(testeeString, 35);
setStore(testeeString, initArray);

String[] mediumArray = new String[9];
String[] refArray = new String[mediumArray.length];

for (int i = 0; i < mediumArray.length; i++ ) {
mediumArray[i] = Integer.toBinaryString(rnd.nextInt(100) + 67);
refArray[i] = mediumArray[i];
}
Object[] storeArr = getStore(testeeString);
testeeString.fromArray(mediumArray);
int _size = getSize(testeeString);
assertEquals("_size should be set to arr's length in fromArray()", 9, _size);
Object[] newStore = getStore(testeeString);
assertSame("fromArray() should not allocate a new array for _store unless _store is smaller than arr!", storeArr,
newStore);
for (int i = 0; i < refArray.length; i++ ) {
assertSame("fromArray() should have assigned the entries in _store to equal the entries in arr. At index " + i,
refArray[i], newStore[i]);
}
}

@Test
public final void testToArrayEmptyMultiSet() throws Exception {
Object[] storeArr = getStore(testeeInt);
Object[] arr = testeeInt.toArray();
Object[] newStore = getStore(testeeInt);
assertNotNull("toArray() should return an array even when MultiSet is empty!", arr);
assertNotSame("toArray() should not return _store", arr, newStore);
assertEquals("toArray() should return array with length equal to the multiset size", 0, arr.length);
int _size = getSize(testeeInt);
assertEquals("_size should not change in toArray()", 0, _size);
assertSame("_store should not change in toArray()", storeArr, newStore);
}

@Test
public final void testToArrayNonEmpty() throws Exception {
String[] initArray = new String[64];
Random rnd = new Random();
for (int i = 0; i < 35; i++ ) {
initArray[i] = Integer.toHexString(rnd.nextInt(67));
}
setSize(testeeString, 35);
setStore(testeeString, initArray);

Object[] arr = testeeString.toArray();
Object[] newStore = getStore(testeeString);
assertNotNull("toArray() should return an array and not null", arr);
assertNotSame("toArray() should not return _store", arr, initArray);
assertEquals("toArray() should return array with length equal to the multiset size", 35, arr.length);
int _size = getSize(testeeString);
assertEquals("_size should not change in toArray()", 35, _size);
assertSame("_store should not change in toArray()", initArray, newStore);
}

private Field storeField;
private Field sizeField;

@Before
public final void checkFieldsUnchanged() {
Class mSet = ArrayMultiSet.class;
Field[] fields = mSet.getDeclaredFields();
assertEquals("You should not add any fields to the ArrayMultiSet class. This class's field count:", 3,
fields.length);
try {
Field defaultStoreLengthCount = mSet.getDeclaredField("DEFAULT_INITIAL_CAPACITY");
assertEquals("The DEFAULT_INITIAL_CAPACITY field should be of type int", Integer.TYPE,
defaultStoreLengthCount.getType());
int mods = defaultStoreLengthCount.getModifiers();
assertTrue("The DEFAULT_INITIAL_CAPACITY field should still be static", Modifier.isStatic(mods));
assertTrue("The DEFAULT_INITIAL_CAPACITY field should still be final", Modifier.isFinal(mods));
} catch (Exception e) {
fail("Your ArrayMultiSet class should still define a field named \"DEFAULT_STORE_LENGTH\"");
}
try {
storeField = mSet.getDeclaredField("_store");
assertTrue("The _store field should be an 1-d array", storeField.getType().isArray());
assertEquals("The _store field should be an 1-d array", Object.class, storeField.getType().getComponentType());
storeField.setAccessible(true);
} catch (Exception e) {
fail("Your ArrayMultiSet class should still define a field named \"_store\"");
}
try {
sizeField = mSet.getDeclaredField("_size");
assertEquals("The _size field should be of type int", Integer.TYPE, sizeField.getType());
sizeField.setAccessible(true);
} catch (Exception e) {
fail("Your ArrayMultiSet class should still define a field named \"_size\"");
}
testeeInt = new ArrayMultiSet<>();
testeeString = new ArrayMultiSet<>();
}

private int getSize(ArrayMultiSet testee) throws Exception {
return sizeField.getInt(testee);
}

private void setSize(ArrayMultiSet testee, int newNumber) throws Exception {
sizeField.setInt(testee, newNumber);
}

private Object[] getStore(ArrayMultiSet testee) throws Exception {
return (Object[]) storeField.get(testee);
}

private void setStore(ArrayMultiSet testee, Object[] newStore) throws Exception {
storeField.set(testee, newStore);
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hi, I have implemented required methods: toArray and fromArray

Since you have not provided implementation of "add" or other methods, so i can not test.

Please test both methods and let me know in case of any issue.

import java.util.Collection;

import java.util.Iterator;

/**

* Class which implements the concept of a multiset -- an unorganized collection which does not limited the number of

* times an instance can be added.

*

* @author Carl Alphonse

* @author Matthew Hertz

* @param Type of data contained with the instance.

*/

public class ArrayMultiSet<E> implements Collection<E> {

   /** Unless otherwise specified, the default length to which the backing store should be initialized. */

   private static final int DEFAULT_INITIAL_CAPACITY = 16;

   /** Array in which the elements in this multiset are stored. */

   private E[] _store;

   /**

   * Array indices below this amount contain the active elements in this collection.

   */

   private int _size;

   /**

   * Create a new empty multiset.

   */

   public ArrayMultiSet() {

       clear();

   }

   /**

   * Remove all of the elements within the instance and invalidate any current iterators.

   */

   @SuppressWarnings("unchecked")

   @Override

   public void clear() {

       _store = (E[]) (new Object[DEFAULT_INITIAL_CAPACITY]);

       _size = 0;

   }

   @Override

   public int size() {

       return _size;

   }

   @Override

   public boolean isEmpty() {

       return _size == 0;

   }

   /**

   * Returns a newly allocated array containing the elements in the Multiset. The length of returned array will be the

   * current size of the Multiset with no padding or extra spaces added.

   *

   * @return Newly allocated array whose entries are set to the elements in the Multiset.

   */

   @Override

   public Object[] toArray() {

      

       @SuppressWarnings("unchecked")

       E[] newArr = (E[]) (new Object[_size]);

      

       for(int i=0; i<_size; i++) {

           newArr[i] = _store[i];

       }

  

       return newArr;

   }

   /**

   * Resets the Multiset so that it only contains the entries in the given array. This overwrites the data previously in

   * the Collection.

   *

   * @param arr The array whose entries will be the elements in the Collection

   */

   @SuppressWarnings("unchecked")

   public void fromArray(E[] arr) {

       // IMPORTANT: You CANNOT set the backing store to be equal to ("alias")

       // arr. If you did this, the calling method could make changes to the

       // Multiset by updating the entries in arr rather than using the Multiset methods.

       // This violates good OO practice and creates the potential for bugs and hacks.

      

       if(_store.length < arr.length) {

           _store = (E[]) (new Object[arr.length]);

           _size = 0;

       }

      

       for(int i=0; i<arr.length; i++) {

           _store[i] = arr[i];

       }

       _size = arr.length;

   }

   /**

   * Update the multiset so that it includes all of the elements from before the call AND the given element.

   *

   * @param e Item to be added to this collection.

   */

   @Override

   public boolean add(E e) {

       // To be discussed on Friday!

       throw new UnsupportedOperationException();

   }

   /**

   * Removes a single instance of the given object, if one can be found in the multiset. The method returns {@code true}

   * if a match was found (and removed) and {@code false} if no match was found. Normally, this uses

   * {@link Object#equals} to check if there is a match, but uses {@code ==} when {@code obj} is {@code null}.

   *

   * @param obj Object (or null) which we want to remove

   * @return {@code true} if {@code obj} was found and an instance removed; {@code false} if a match could not be found.

   */

   @Override

   public boolean remove(Object obj) {

       // To be discussed Monday!

       throw new UnsupportedOperationException();

   }

   /**

   * Return true if at least one element in the multiset is equal to the given object. When {@code obj} is null, it must

   * use the {@code ==} operator to perform these checks, but when {@code obj} is not null, the {@link Object#equals}

   * method is used.

   *

   * @param obj Object (or null) for which we will search

   * @return {@code true} if {@code obj} was found and an instance removed; {@code false} if a match could not be found.

   */

   @Override

   public boolean contains(Object obj) {

       // To be discussed Monday!

       throw new UnsupportedOperationException();

   }

   /*

   * The remaining methods are part of the Collection interface, but are beyond what is necessary for CSE 116.

   * Students who want a complete Multiset implementation should investigate Google's "Guava" library.

   */

   @Override

   public Iterator iterator() {

       throw new UnsupportedOperationException();

   }

   @Override

   public T[] toArray(T[] a) {

       throw new UnsupportedOperationException();

   }

   @Override

   public boolean containsAll(Collection c) {

       throw new UnsupportedOperationException();

   }

   @Override

   public boolean addAll(Collection c) {

       throw new UnsupportedOperationException();

   }

   @Override

   public boolean removeAll(Collection c) {

       throw new UnsupportedOperationException();

   }

   @Override

   public boolean retainAll(Collection c) {

       throw new UnsupportedOperationException();

   }

   @Override

   public Object[] toArray(Object[] a) {

       // TODO Auto-generated method stub

       return null;

   }

   @Override

   public boolean add(Object e) {

       // TODO Auto-generated method stub

       return false;

   }

}

Add a comment
Know the answer?
Add Answer to:
This wont take you more than 15 mins. Comple the two method and besure to test...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Can someone please explain this piece of java code line by line as to what they...

    Can someone please explain this piece of java code line by line as to what they are doing and the purpose of each line (you can put it in the code comments). Code: import java.util.*; public class Array { private Integer[] array; // NOTE: Integer is an Object. Array() {     super();     array = new Integer[0]; } Array(Array other) {     super();     array = other.array.clone(); // NOTE: All arrays can be cloned. } void add(int value) {    ...

  • I am not passing some of the code when i run the testing . PriorityQueue public...

    I am not passing some of the code when i run the testing . PriorityQueue public class PriorityQueue<T extends Comparable<T>> implements IPriorityQueue<T> {    private Vector<T> theVector = new Vector<>(0, 1);    private int size = 0;    @Override    public void insert(T element) {        theVector.pushBack(element);        size++;        bubbleUp(); }    @Override    public T peekTop() throws java.util.NoSuchElementException {        if (isEmpty()) {            throw new java.util.NoSuchElementException();        }       ...

  • Im having trouble implimenting the addAll method.. import java.util.Collection; public interface Tree<E> extends Collection<E> { /**...

    Im having trouble implimenting the addAll method.. import java.util.Collection; public interface Tree<E> extends Collection<E> { /** Return true if the element is in the tree */ public boolean search(E e); /** Insert element e into the binary tree * Return true if the element is inserted successfully */ public boolean insert(E e); /** Delete the specified element from the tree * Return true if the element is deleted successfully */ public boolean delete(E e);    /** Get the number of...

  • instructions: Write a non-member method named bagScaler, which removes from a Bag all elements that occur...

    instructions: Write a non-member method named bagScaler, which removes from a Bag all elements that occur less than N times . The method returns the number of copies removed. For example, if B = {Bob, Joe, Bob, Ned, Bob, Ned, Kim}, then calling bagScaler(B, 3) removes Joe, Ned, and Kim making B = {Bob, Bob, Bob}, and returns 4 because it removed 2 copies of Ned, one of Joe, and one of Kim. Note: There's no iterator, but there is...

  • Java implement the method in IteratorExercise.java using only list iterator methods: bubbleSort: sort the provided list...

    Java implement the method in IteratorExercise.java using only list iterator methods: bubbleSort: sort the provided list using bubble sort Do not modify the test code in each function. You can look at that code for some ideas for implementing the methods. import java.lang.Comparable; import java.util.*; public class IteratorExercise {       public static <E extends Comparable<? super E>> void bubbleSort(List<E> c) throws Exception {        // first line to start you off        ListIterator<E> iit = c.listIterator(), jit;...

  • Study the recursive instance method length()of MyLinkedList2 class and its associated auxiliary method. Then solve (a),...

    Study the recursive instance method length()of MyLinkedList2 class and its associated auxiliary method. Then solve (a), (b), and (c) below in a similar way: (a)   Convert the method public Element find(Object obj)of MyLinkedList2 class to a recursive one. Use an auxiliary private method. (b)   Convert the method public String toString( )of MyLinkedList2 class to a recursive one such that it returns the string representation of a linked list in the form: {ValueDatum1  valueDatum2 valueDatum3  . . .  valueDatumN-1   valueDatumN} Use an auxiliary private method....

  • IN JAVA: Write a class, ZeroException, which is an Exception, and is used to signal that somethi...

    IN JAVA: Write a class, ZeroException, which is an Exception, and is used to signal that something is zero when it shouldn't be. Write the class ArrayManipulator which creates an array and provides several methods to manipulate values taken from an array. ZeroException Task: Exceptions are used to signal many types of problems in a program. We can write our own as well to describe specific exceptional conditions which may arise. The advantage of doing so is that when exceptions...

  • Junit test provided, won't take you more than 15 mins. Be sure you can pass the...

    Junit test provided, won't take you more than 15 mins. Be sure you can pass the test. --------------------------------------------------------- For this problem you will need to write the Square superclass and 2 subclasses of Square. The name of each of the classes you will write and the work they must do is as follows: Square Define an instance-based field of type double named length. Make certain the field has proper access protections. You should also define a getter & setter for...

  • Comparing the insertion and removing performance between ALPQueue with HeapPQueue. Requirements: ...

    Comparing the insertion and removing performance between ALPQueue with HeapPQueue. Requirements: 1/ Task1: implement a concrete ALPQueue class (an ArrayList based priority queue) that extends the AbstractPQueue discussed in the class, along with PQueue.java, ArrayList.java, List.java, PQEntry.java , EntryComparitor.java, and OutOfRangeException.java given in the class (any other implementation of above classes that are not compatible with List interface and AbstractPQueue class will not receive any credit). 2/ Task2: implement a concrete HeapPQueue class (a Heap based priority queue) that extends...

  • Comparing the insertion and removing performance between ALPQueue with HeapPQueue. Requirements: 1/ Task1: implement a concrete...

    Comparing the insertion and removing performance between ALPQueue with HeapPQueue. Requirements: 1/ Task1: implement a concrete ALPQueue class (an ArrayList based priority queue) that extends the AbstractPQueue discussed in the class, along with PQueue.java, ArrayList.java, List.java, PQEntry.java , EntryComparitor.java, and OutOfRangeException.java given in the class (any other implementation of above classes that are not compatible with List interface and AbstractPQueue class will not receive any credit). 2/ Task2: implement a concrete HeapPQueue class (a Heap based priority queue) that extends...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT