SlideShare a Scribd company logo
1 of 7
Download to read offline
This file contains a complete array-based MultiSet, but not the code needed to support its
Iterator. Complete the Iterator's next() and hasNext() methods.
Solution
Hi, I have implemented both required methods.
Please let me know in case of any issue.
import java.util.Collection;
import java.util.Iterator;
public class ArrayMultiSet implements Collection {
/** 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;
/**
* Modification counter used to preserve the fail-fast nature of its iterators.
*/
private long _modCount;
/**
* Create a new empty multiset.
*/
public ArrayMultiSet() {
_modCount = 0;
clear();
}
/**
* Remove all of the elements within the instance and invalidate any current iterators.
*/
@SuppressWarnings("unchecked")
@Override
public void clear() {
_store = (E[]) (new Object[16]);
_size = 0;
// maintains the class invariant
}
/**
* 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.
*/
@SuppressWarnings("unchecked")
@Override
public boolean add(E e) {
// Check if we do not have enough space in the underlying array to store the
// new element
if (_size == _store.length) {
// We do not have space, so create a new larger space (doubling the size
// is the most time efficient)
E[] newStore = (E[]) new Object[_store.length * 2];
// Copy all of the references into the new array
for (int i = 0; i < _store.length; i++ ) {
newStore[i] = _store[i];
}
_store = newStore;
// An easier, more efficient way of coding this (but less useful for
// teaching) would instead be:
// _store = Arrays.copyOf(_store, _store.length * 2);
}
// Add the element to the store
_store[_size] = e;
// Finally, we can increase _size, since this change will no longer violate
// any class invariants.
_size += 1;
return true;
}
/**
* 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; {@code false} if a match could not be
found.
*/
@Override
public boolean contains(Object obj) {
// Only scan through _size, since those are the only "real" entries for the
// multiset.
for (int i = 0; i < _size; i++ ) {
// When obj is null, we need to use ==
if ((obj == null) && (_store[i] == null)) {
return true;
}
// Otherwise, we use .equals() to find a match
else if ((obj != null) && obj.equals(_store[i])) {
return true;
}
// No else clause, since the match could be at a higher index!
}
// Checked all VALID indices, so the result must be:
return false;
}
@Override
public int size() {
return _size;
}
/**
* Remove the element found at the given index. This method also acts to maintain the class
invariants.
* Precondition: {@code i} is a valid index within {@code _store}.
*
* @param i Index of the element to remove from the multibag.
*/
private void removeAtIndex(int i) {
// We do not need to check i, since we made that a precondition (assumption)
// for this method.
// Use the last element in the backing store to fill the hole made by the removal.
_store[i] = _store[_size - 1];
// Set that last value to null (this is not necessary, but can help optimize performance)
_store[_size - 1] = null;
// Finally, decrease the value of size
_size -= 1;
}
/**
* Removes a single instance of the given object, if one can be found in the multibag. 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) {
for (int i = 0; i < _size; i++ ) {
if ((obj == null) && (_store[i] == null)) {
removeAtIndex(i);
return true;
} else if ((obj != null) && obj.equals(_store[i])) {
removeAtIndex(i);
return true;
}
// No else clause, since a match may still exist at a higher index!
}
// Checked all VALID indices, so the result must be:
return false;
}
@Override
public boolean isEmpty() {
return _size == 0;
}
@Override
public Iterator iterator() {
return new MultiSetIterator();
}
/**
* Instances of this class are used as the iterators for a multiset. We must keep this as an inner-
class, because the
* multiset definition does not include any methods to access its elements.
*
* @author Carl Alphonce
* @author Matthew Hertz
*/
private class MultiSetIterator implements Iterator {
/**
* The index of the _store entry which will be returned by the next call to next()
*/
private int _cursor;
/**
* In keeping with the fail-fast convention, the iterator is only valid while _modCount
remains on this version.
*/
private long _collectionVersion;
/**
* Create a new instance of this class that will go through the (valid) entries in the store.
*/
public MultiSetIterator() {
_cursor = 0;
_collectionVersion = _modCount;
}
public boolean hasNext() {
return _cursor < _size;
}
public E next() {
return _store[_cursor++];
}
public void remove() {
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 Object[] toArray() {
// TODO Auto-generated method stub
return null;
}
@Override
public T[] toArray(T[] a) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean containsAll(Collection c) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean addAll(Collection c) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean removeAll(Collection c) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean retainAll(Collection c) {
// TODO Auto-generated method stub
return false;
}
}

More Related Content

Similar to This file contains a complete array-based MultiSet, but not the code.pdf

Here is what I got so far, I dont know how to write union, interse.pdf
Here is what I got so far, I dont know how to write union, interse.pdfHere is what I got so far, I dont know how to write union, interse.pdf
Here is what I got so far, I dont know how to write union, interse.pdfarihantpatna
 
week4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docx
week4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docxweek4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docx
week4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docxalanfhall8953
 
Hello need help on this lab- what you need to do is add a code to Arra.pdf
Hello need help on this lab- what you need to do is add a code to Arra.pdfHello need help on this lab- what you need to do is add a code to Arra.pdf
Hello need help on this lab- what you need to do is add a code to Arra.pdfIan0J2Bondo
 
Stack Implementation
Stack ImplementationStack Implementation
Stack ImplementationZidny Nafan
 
Write a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdfWrite a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdfeyebolloptics
 
using the code below write the public V add(K key, V value); that ad.pdf
using the code below write the public V add(K key, V value); that ad.pdfusing the code below write the public V add(K key, V value); that ad.pdf
using the code below write the public V add(K key, V value); that ad.pdfamirthagiftsmadurai
 
public class DoubleArraySeq implements Cloneable {    Priva.pdf
public class DoubleArraySeq implements Cloneable {     Priva.pdfpublic class DoubleArraySeq implements Cloneable {     Priva.pdf
public class DoubleArraySeq implements Cloneable {    Priva.pdfannaimobiles
 
Please help me to make a programming project I have to sue them today- (1).pdf
Please help me to make a programming project I have to sue them today- (1).pdfPlease help me to make a programming project I have to sue them today- (1).pdf
Please help me to make a programming project I have to sue them today- (1).pdfseoagam1
 
A generic queue is a general queue storage that can store an.pdf
A generic queue is a general queue storage that can store an.pdfA generic queue is a general queue storage that can store an.pdf
A generic queue is a general queue storage that can store an.pdfADITIHERBAL
 
A generic queue is a general queue storage that can store an.pdf
A generic queue is a general queue storage that can store an.pdfA generic queue is a general queue storage that can store an.pdf
A generic queue is a general queue storage that can store an.pdfadhityafashion
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfinfo309708
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7Vince Vo
 
Create a Dynamic Array container with this user interface Ge.pdf
Create a Dynamic Array container with this user interface  Ge.pdfCreate a Dynamic Array container with this user interface  Ge.pdf
Create a Dynamic Array container with this user interface Ge.pdfsktambifortune
 
Oop lect3.pptx
Oop lect3.pptxOop lect3.pptx
Oop lect3.pptxMrMudassir
 
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdfUsing c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdffashiongallery1
 
we using java code DynamicArrayjava Replace all .pdf
we using java code   DynamicArrayjava   Replace all .pdfwe using java code   DynamicArrayjava   Replace all .pdf
we using java code DynamicArrayjava Replace all .pdfgudduraza28
 
Alcohol Awareness Special Lecture ReflectionAlcohol is among the.docx
Alcohol Awareness Special Lecture ReflectionAlcohol is among the.docxAlcohol Awareness Special Lecture ReflectionAlcohol is among the.docx
Alcohol Awareness Special Lecture ReflectionAlcohol is among the.docxsimonlbentley59018
 

Similar to This file contains a complete array-based MultiSet, but not the code.pdf (20)

Here is what I got so far, I dont know how to write union, interse.pdf
Here is what I got so far, I dont know how to write union, interse.pdfHere is what I got so far, I dont know how to write union, interse.pdf
Here is what I got so far, I dont know how to write union, interse.pdf
 
week4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docx
week4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docxweek4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docx
week4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docx
 
Hello need help on this lab- what you need to do is add a code to Arra.pdf
Hello need help on this lab- what you need to do is add a code to Arra.pdfHello need help on this lab- what you need to do is add a code to Arra.pdf
Hello need help on this lab- what you need to do is add a code to Arra.pdf
 
Stack Implementation
Stack ImplementationStack Implementation
Stack Implementation
 
Write a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdfWrite a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdf
 
using the code below write the public V add(K key, V value); that ad.pdf
using the code below write the public V add(K key, V value); that ad.pdfusing the code below write the public V add(K key, V value); that ad.pdf
using the code below write the public V add(K key, V value); that ad.pdf
 
public class DoubleArraySeq implements Cloneable {    Priva.pdf
public class DoubleArraySeq implements Cloneable {     Priva.pdfpublic class DoubleArraySeq implements Cloneable {     Priva.pdf
public class DoubleArraySeq implements Cloneable {    Priva.pdf
 
Please help me to make a programming project I have to sue them today- (1).pdf
Please help me to make a programming project I have to sue them today- (1).pdfPlease help me to make a programming project I have to sue them today- (1).pdf
Please help me to make a programming project I have to sue them today- (1).pdf
 
A generic queue is a general queue storage that can store an.pdf
A generic queue is a general queue storage that can store an.pdfA generic queue is a general queue storage that can store an.pdf
A generic queue is a general queue storage that can store an.pdf
 
A generic queue is a general queue storage that can store an.pdf
A generic queue is a general queue storage that can store an.pdfA generic queue is a general queue storage that can store an.pdf
A generic queue is a general queue storage that can store an.pdf
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Create a Dynamic Array container with this user interface Ge.pdf
Create a Dynamic Array container with this user interface  Ge.pdfCreate a Dynamic Array container with this user interface  Ge.pdf
Create a Dynamic Array container with this user interface Ge.pdf
 
Oop lect3.pptx
Oop lect3.pptxOop lect3.pptx
Oop lect3.pptx
 
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdfUsing c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
 
Enumerable
EnumerableEnumerable
Enumerable
 
Maze
MazeMaze
Maze
 
we using java code DynamicArrayjava Replace all .pdf
we using java code   DynamicArrayjava   Replace all .pdfwe using java code   DynamicArrayjava   Replace all .pdf
we using java code DynamicArrayjava Replace all .pdf
 
Alcohol Awareness Special Lecture ReflectionAlcohol is among the.docx
Alcohol Awareness Special Lecture ReflectionAlcohol is among the.docxAlcohol Awareness Special Lecture ReflectionAlcohol is among the.docx
Alcohol Awareness Special Lecture ReflectionAlcohol is among the.docx
 

More from deepaksatrker

Develop an encryption and decryption algorithm Your program should a.pdf
Develop an encryption and decryption algorithm  Your program should a.pdfDevelop an encryption and decryption algorithm  Your program should a.pdf
Develop an encryption and decryption algorithm Your program should a.pdfdeepaksatrker
 
Cystic fibrosis is caused by a recessive mutant allele (cf). Two norm.pdf
Cystic fibrosis is caused by a recessive mutant allele (cf). Two norm.pdfCystic fibrosis is caused by a recessive mutant allele (cf). Two norm.pdf
Cystic fibrosis is caused by a recessive mutant allele (cf). Two norm.pdfdeepaksatrker
 
Compute the addition and multiplication of the following 2 binary fl.pdf
Compute the addition and multiplication of the following 2 binary fl.pdfCompute the addition and multiplication of the following 2 binary fl.pdf
Compute the addition and multiplication of the following 2 binary fl.pdfdeepaksatrker
 
BIOCHEMList and briefly describe the six types of the 6 basic rec.pdf
BIOCHEMList and briefly describe the six types of the 6 basic rec.pdfBIOCHEMList and briefly describe the six types of the 6 basic rec.pdf
BIOCHEMList and briefly describe the six types of the 6 basic rec.pdfdeepaksatrker
 
Write an audit memo that explains how quality control for an audit e.pdf
Write an audit memo that explains how quality control for an audit e.pdfWrite an audit memo that explains how quality control for an audit e.pdf
Write an audit memo that explains how quality control for an audit e.pdfdeepaksatrker
 
What legal impacts did the ACA have on tax-exempt hospitalsSolu.pdf
What legal impacts did the ACA have on tax-exempt hospitalsSolu.pdfWhat legal impacts did the ACA have on tax-exempt hospitalsSolu.pdf
What legal impacts did the ACA have on tax-exempt hospitalsSolu.pdfdeepaksatrker
 
Which members of the family above are afflicted with Huntingtons Di.pdf
Which members of the family above are afflicted with Huntingtons Di.pdfWhich members of the family above are afflicted with Huntingtons Di.pdf
Which members of the family above are afflicted with Huntingtons Di.pdfdeepaksatrker
 
What could be the arguments of a production functionA Cost and La.pdf
What could be the arguments of a production functionA Cost and La.pdfWhat could be the arguments of a production functionA Cost and La.pdf
What could be the arguments of a production functionA Cost and La.pdfdeepaksatrker
 
What are the benefits to firms of international diversification Wha.pdf
What are the benefits to firms of international diversification Wha.pdfWhat are the benefits to firms of international diversification Wha.pdf
What are the benefits to firms of international diversification Wha.pdfdeepaksatrker
 
What are electromagnetic wavesSolutionWe are encompassed by w.pdf
What are electromagnetic wavesSolutionWe are encompassed by w.pdfWhat are electromagnetic wavesSolutionWe are encompassed by w.pdf
What are electromagnetic wavesSolutionWe are encompassed by w.pdfdeepaksatrker
 
Using RustBecause postfix expressions are simpler and faster to ev.pdf
Using RustBecause postfix expressions are simpler and faster to ev.pdfUsing RustBecause postfix expressions are simpler and faster to ev.pdf
Using RustBecause postfix expressions are simpler and faster to ev.pdfdeepaksatrker
 
tnt en Assignment Nickele Company reoorts net income of sae,4n0 in .pdf
tnt en Assignment Nickele Company reoorts net income of sae,4n0 in .pdftnt en Assignment Nickele Company reoorts net income of sae,4n0 in .pdf
tnt en Assignment Nickele Company reoorts net income of sae,4n0 in .pdfdeepaksatrker
 
The structure of a high temperature superconductor containing barium.pdf
The structure of a high temperature superconductor containing barium.pdfThe structure of a high temperature superconductor containing barium.pdf
The structure of a high temperature superconductor containing barium.pdfdeepaksatrker
 
The present value o.pdf
The present value o.pdfThe present value o.pdf
The present value o.pdfdeepaksatrker
 
The Associated Handles section in Resource Monitor can be used to sh.pdf
The Associated Handles section in Resource Monitor can be used to sh.pdfThe Associated Handles section in Resource Monitor can be used to sh.pdf
The Associated Handles section in Resource Monitor can be used to sh.pdfdeepaksatrker
 
T 5. A contract should be held enforceable even if a party is mistake.pdf
T 5. A contract should be held enforceable even if a party is mistake.pdfT 5. A contract should be held enforceable even if a party is mistake.pdf
T 5. A contract should be held enforceable even if a party is mistake.pdfdeepaksatrker
 
Subject - Project ManagementDescribe what the WBS is and why you .pdf
Subject - Project ManagementDescribe what the WBS is and why you .pdfSubject - Project ManagementDescribe what the WBS is and why you .pdf
Subject - Project ManagementDescribe what the WBS is and why you .pdfdeepaksatrker
 
Significant mass extinctions occurred during which of the following .pdf
Significant mass extinctions occurred during which of the following .pdfSignificant mass extinctions occurred during which of the following .pdf
Significant mass extinctions occurred during which of the following .pdfdeepaksatrker
 
SOLUTIONNotice thatt2becomes simpler when differentiated (wherease5t.pdf
SOLUTIONNotice thatt2becomes simpler when differentiated (wherease5t.pdfSOLUTIONNotice thatt2becomes simpler when differentiated (wherease5t.pdf
SOLUTIONNotice thatt2becomes simpler when differentiated (wherease5t.pdfdeepaksatrker
 
Please help with the English test !!! Thank you very much!Identify.pdf
Please help with the English test !!! Thank you very much!Identify.pdfPlease help with the English test !!! Thank you very much!Identify.pdf
Please help with the English test !!! Thank you very much!Identify.pdfdeepaksatrker
 

More from deepaksatrker (20)

Develop an encryption and decryption algorithm Your program should a.pdf
Develop an encryption and decryption algorithm  Your program should a.pdfDevelop an encryption and decryption algorithm  Your program should a.pdf
Develop an encryption and decryption algorithm Your program should a.pdf
 
Cystic fibrosis is caused by a recessive mutant allele (cf). Two norm.pdf
Cystic fibrosis is caused by a recessive mutant allele (cf). Two norm.pdfCystic fibrosis is caused by a recessive mutant allele (cf). Two norm.pdf
Cystic fibrosis is caused by a recessive mutant allele (cf). Two norm.pdf
 
Compute the addition and multiplication of the following 2 binary fl.pdf
Compute the addition and multiplication of the following 2 binary fl.pdfCompute the addition and multiplication of the following 2 binary fl.pdf
Compute the addition and multiplication of the following 2 binary fl.pdf
 
BIOCHEMList and briefly describe the six types of the 6 basic rec.pdf
BIOCHEMList and briefly describe the six types of the 6 basic rec.pdfBIOCHEMList and briefly describe the six types of the 6 basic rec.pdf
BIOCHEMList and briefly describe the six types of the 6 basic rec.pdf
 
Write an audit memo that explains how quality control for an audit e.pdf
Write an audit memo that explains how quality control for an audit e.pdfWrite an audit memo that explains how quality control for an audit e.pdf
Write an audit memo that explains how quality control for an audit e.pdf
 
What legal impacts did the ACA have on tax-exempt hospitalsSolu.pdf
What legal impacts did the ACA have on tax-exempt hospitalsSolu.pdfWhat legal impacts did the ACA have on tax-exempt hospitalsSolu.pdf
What legal impacts did the ACA have on tax-exempt hospitalsSolu.pdf
 
Which members of the family above are afflicted with Huntingtons Di.pdf
Which members of the family above are afflicted with Huntingtons Di.pdfWhich members of the family above are afflicted with Huntingtons Di.pdf
Which members of the family above are afflicted with Huntingtons Di.pdf
 
What could be the arguments of a production functionA Cost and La.pdf
What could be the arguments of a production functionA Cost and La.pdfWhat could be the arguments of a production functionA Cost and La.pdf
What could be the arguments of a production functionA Cost and La.pdf
 
What are the benefits to firms of international diversification Wha.pdf
What are the benefits to firms of international diversification Wha.pdfWhat are the benefits to firms of international diversification Wha.pdf
What are the benefits to firms of international diversification Wha.pdf
 
What are electromagnetic wavesSolutionWe are encompassed by w.pdf
What are electromagnetic wavesSolutionWe are encompassed by w.pdfWhat are electromagnetic wavesSolutionWe are encompassed by w.pdf
What are electromagnetic wavesSolutionWe are encompassed by w.pdf
 
Using RustBecause postfix expressions are simpler and faster to ev.pdf
Using RustBecause postfix expressions are simpler and faster to ev.pdfUsing RustBecause postfix expressions are simpler and faster to ev.pdf
Using RustBecause postfix expressions are simpler and faster to ev.pdf
 
tnt en Assignment Nickele Company reoorts net income of sae,4n0 in .pdf
tnt en Assignment Nickele Company reoorts net income of sae,4n0 in .pdftnt en Assignment Nickele Company reoorts net income of sae,4n0 in .pdf
tnt en Assignment Nickele Company reoorts net income of sae,4n0 in .pdf
 
The structure of a high temperature superconductor containing barium.pdf
The structure of a high temperature superconductor containing barium.pdfThe structure of a high temperature superconductor containing barium.pdf
The structure of a high temperature superconductor containing barium.pdf
 
The present value o.pdf
The present value o.pdfThe present value o.pdf
The present value o.pdf
 
The Associated Handles section in Resource Monitor can be used to sh.pdf
The Associated Handles section in Resource Monitor can be used to sh.pdfThe Associated Handles section in Resource Monitor can be used to sh.pdf
The Associated Handles section in Resource Monitor can be used to sh.pdf
 
T 5. A contract should be held enforceable even if a party is mistake.pdf
T 5. A contract should be held enforceable even if a party is mistake.pdfT 5. A contract should be held enforceable even if a party is mistake.pdf
T 5. A contract should be held enforceable even if a party is mistake.pdf
 
Subject - Project ManagementDescribe what the WBS is and why you .pdf
Subject - Project ManagementDescribe what the WBS is and why you .pdfSubject - Project ManagementDescribe what the WBS is and why you .pdf
Subject - Project ManagementDescribe what the WBS is and why you .pdf
 
Significant mass extinctions occurred during which of the following .pdf
Significant mass extinctions occurred during which of the following .pdfSignificant mass extinctions occurred during which of the following .pdf
Significant mass extinctions occurred during which of the following .pdf
 
SOLUTIONNotice thatt2becomes simpler when differentiated (wherease5t.pdf
SOLUTIONNotice thatt2becomes simpler when differentiated (wherease5t.pdfSOLUTIONNotice thatt2becomes simpler when differentiated (wherease5t.pdf
SOLUTIONNotice thatt2becomes simpler when differentiated (wherease5t.pdf
 
Please help with the English test !!! Thank you very much!Identify.pdf
Please help with the English test !!! Thank you very much!Identify.pdfPlease help with the English test !!! Thank you very much!Identify.pdf
Please help with the English test !!! Thank you very much!Identify.pdf
 

Recently uploaded

Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 

Recently uploaded (20)

Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 

This file contains a complete array-based MultiSet, but not the code.pdf

  • 1. This file contains a complete array-based MultiSet, but not the code needed to support its Iterator. Complete the Iterator's next() and hasNext() methods. Solution Hi, I have implemented both required methods. Please let me know in case of any issue. import java.util.Collection; import java.util.Iterator; public class ArrayMultiSet implements Collection { /** 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; /** * Modification counter used to preserve the fail-fast nature of its iterators. */ private long _modCount; /** * Create a new empty multiset. */ public ArrayMultiSet() { _modCount = 0; clear(); } /** * Remove all of the elements within the instance and invalidate any current iterators. */ @SuppressWarnings("unchecked") @Override public void clear() { _store = (E[]) (new Object[16]); _size = 0;
  • 2. // maintains the class invariant } /** * 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. */ @SuppressWarnings("unchecked") @Override public boolean add(E e) { // Check if we do not have enough space in the underlying array to store the // new element if (_size == _store.length) { // We do not have space, so create a new larger space (doubling the size // is the most time efficient) E[] newStore = (E[]) new Object[_store.length * 2]; // Copy all of the references into the new array for (int i = 0; i < _store.length; i++ ) { newStore[i] = _store[i]; } _store = newStore; // An easier, more efficient way of coding this (but less useful for // teaching) would instead be: // _store = Arrays.copyOf(_store, _store.length * 2); } // Add the element to the store _store[_size] = e; // Finally, we can increase _size, since this change will no longer violate // any class invariants. _size += 1; return true; } /** * Return true if at least one element in the multiset is equal to the given object. When {@code obj} is null, it must
  • 3. * 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; {@code false} if a match could not be found. */ @Override public boolean contains(Object obj) { // Only scan through _size, since those are the only "real" entries for the // multiset. for (int i = 0; i < _size; i++ ) { // When obj is null, we need to use == if ((obj == null) && (_store[i] == null)) { return true; } // Otherwise, we use .equals() to find a match else if ((obj != null) && obj.equals(_store[i])) { return true; } // No else clause, since the match could be at a higher index! } // Checked all VALID indices, so the result must be: return false; } @Override public int size() { return _size; } /** * Remove the element found at the given index. This method also acts to maintain the class invariants. * Precondition: {@code i} is a valid index within {@code _store}. *
  • 4. * @param i Index of the element to remove from the multibag. */ private void removeAtIndex(int i) { // We do not need to check i, since we made that a precondition (assumption) // for this method. // Use the last element in the backing store to fill the hole made by the removal. _store[i] = _store[_size - 1]; // Set that last value to null (this is not necessary, but can help optimize performance) _store[_size - 1] = null; // Finally, decrease the value of size _size -= 1; } /** * Removes a single instance of the given object, if one can be found in the multibag. 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) { for (int i = 0; i < _size; i++ ) { if ((obj == null) && (_store[i] == null)) { removeAtIndex(i); return true; } else if ((obj != null) && obj.equals(_store[i])) { removeAtIndex(i); return true; } // No else clause, since a match may still exist at a higher index! }
  • 5. // Checked all VALID indices, so the result must be: return false; } @Override public boolean isEmpty() { return _size == 0; } @Override public Iterator iterator() { return new MultiSetIterator(); } /** * Instances of this class are used as the iterators for a multiset. We must keep this as an inner- class, because the * multiset definition does not include any methods to access its elements. * * @author Carl Alphonce * @author Matthew Hertz */ private class MultiSetIterator implements Iterator { /** * The index of the _store entry which will be returned by the next call to next() */ private int _cursor; /** * In keeping with the fail-fast convention, the iterator is only valid while _modCount remains on this version. */ private long _collectionVersion; /** * Create a new instance of this class that will go through the (valid) entries in the store. */ public MultiSetIterator() { _cursor = 0; _collectionVersion = _modCount; }
  • 6. public boolean hasNext() { return _cursor < _size; } public E next() { return _store[_cursor++]; } public void remove() { 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 Object[] toArray() { // TODO Auto-generated method stub return null; } @Override public T[] toArray(T[] a) { // TODO Auto-generated method stub return null; } @Override public boolean containsAll(Collection c) { // TODO Auto-generated method stub return false; } @Override public boolean addAll(Collection c) { // TODO Auto-generated method stub return false; }
  • 7. @Override public boolean removeAll(Collection c) { // TODO Auto-generated method stub return false; } @Override public boolean retainAll(Collection c) { // TODO Auto-generated method stub return false; } }