SlideShare a Scribd company logo
1 of 13
Download to read offline
Array with Iterator. Java style
Implement an array data structure as a class JstyArray to support the Iterable interface such that
the following code works:
The iterator provided by this class follows the behaviour of typical Java style (Jsty). If the
underlying collection is modified, the iterator becomes invalid and an exception is raised.
An example of code that may generate an exception is below:
There are 4 necessary methods for the Array. get(), set(), remove() and iterator().
There are 2 necessary methods for Iterator. hasNext() and next().
Other than these, you need to create more methods for communicating between Array and the
Iterator. Object references are very useful in this scenario.
Once you have an iterator going. There is the next step of handling multiple iterators for the
same data structure. More than one iterator can exist, at different times. There are iterators which
are
•are invalid and have raised an exception, or
•are invalid and have not yet raised an exception, or
•are valid, they were created after modification to the data structure.
Multiple iterators are one of the harder tests
THERE ARE TWO CLASSES USED as shown below:
....................................................................................................................
JstyIterator.java:
/*
* An iterator for the class JstyArray. Performs all standard tasks of an iterator.
* Specifically, when calling next() on an invalid iterator, a NoSuchElementException is raised
by this class.
*
*/
import java.util.Iterator;
import java.util.NoSuchElementException;
public class JstyIterator implements Iterator{
private JstyArray array;
private int index;
public JstyIterator(JstyArray array) {
this.array = array;
index = 0;
}
// YOUR CODE ANYWHERE IN THIS CLASS
public boolean hasNext() {
// YOUR CODE ANYWHERE IN THIS CLASS
if (array.size == index)
return false;
else
return true;
}
public E next() throws NoSuchElementException {
// YOUR CODE ANYWHERE IN THIS CLASS
if (array.list.size() != array.size)
throw new NoSuchElementException("Array elements have been modified !");
else if (hasNext()) {
return array.get(index++);
} else {
throw new NoSuchElementException("There are no elements in the array. Size = " +
array.size);
}
}
public void remove() {
// we need this method for the nagging Java compiler
// you may leave empty
}
}
..........................................................................................................................................................
JstyArray.java:
/*
* An array that implements the Iterable interface.
* Returns an iterator that would raise an exception if the array was modified (set or remove)
*
*/
import java.util.LinkedList;
public class JstyArray implements Iterable{
// YOUR CODE ANYWHERE IN THIS CLASS
private E[] array;
public static final int CAPACITY = 100;
public int size;
public int capacity;
public LinkedList list;
// there could be more instance variables!
/*
* initialise array with capacity. If capacity is less than 1, use CAPACITY.
*
*/
@SuppressWarnings("unchecked")
public JstyArray(int capacity) {
// YOUR CODE ANYWHERE IN THIS CLASS
if (capacity
{
array = (E[]) new Object[CAPACITY];
this.capacity = CAPACITY;
list = new LinkedList();
size = 0;
}
else
{
array = (E[]) new Object[capacity];
this.capacity = capacity;
list = new LinkedList();
size = 0;
}
}
/*
* if index is outside range of array. simply return
*
*/
public void set(int i, E val) {
// YOUR CODE ANYWHERE IN THIS CLASS
if (i >= capacity)
return;
else
{
array[i] = val;
list.add(i, val);
size++;
}
}
/*
* if index is outside range of array. return null
*
*/
public E get(int i) {
// YOUR CODE ANYWHERE IN THIS CLASS
if (i >= capacity)
return null;
else
return array[i];
}
/*
* if index is outside range of array. return null
*
*/
public E remove(int i) {
// YOUR CODE ANYWHERE IN THIS CLASS
if (i >= capacity)
return null;
else
{
list.remove(i);
E e = array[i];
array[i] = null;
return e;
}
}
public JstyIterator iterator() {
// YOUR CODE ANYWHERE IN THIS CLASS
return new JstyIterator(this);
}
}
...........................................................................................................................................................
..............
It passes some testcase but not all.
Can you fix my code for it to pass all testcases TESTCASES testremove Begin4 V
testPrintEachNoException testremoveEnd5 V testNested1 testremoveEnd3 V testremove Begin3
X testConsecutiveUseBadGood X testremoveEnd1 X testremoveEnd2 X testremoveEnd4 X
testremoveBegin2 X testremove Single X testConsecutiveUseGoodBadGood
Solution
PROGRAM CODE:
JstyArray.java
package array2;
/*
* An array that implements the Iterable interface.
* Returns an iterator that would raise an exception if the array was modified (set or remove)
*
*/
import java.util.LinkedList;
import java.util.NoSuchElementException;
public class JstyArray implements Iterable{
// YOUR CODE ANYWHERE IN THIS CLASS
private E[] array;
public static final int CAPACITY = 100;
public int size;
public int capacity;
public LinkedList list;
// there could be more instance variables!
/*
* initialise array with capacity. If capacity is less than 1, use CAPACITY.
*
*/
@SuppressWarnings("unchecked")
public JstyArray(int capacity) {
// YOUR CODE ANYWHERE IN THIS CLASS
if (capacity<1)
{
array = (E[]) new Object[CAPACITY];
this.capacity = CAPACITY;
list = new LinkedList();
size = 0;
}
else
{
array = (E[]) new Object[capacity];
this.capacity = capacity;
list = new LinkedList();
size = 0;
}
}
/*
* if index is outside range of array. simply return
*
*/
public void set(int i, E val) {
// YOUR CODE ANYWHERE IN THIS CLASS
if (i >= capacity)
return;
else
{
array[i] = val;
list.add(i, val);
size++;
}
}
/*
* if index is outside range of array. return null
*
*/
public E get(int i) {
// YOUR CODE ANYWHERE IN THIS CLASS
if (i >= capacity)
return null;
else
return array[i];
}
/*
* if index is outside range of array. return null
*
*/
public E remove(int i) {
// YOUR CODE ANYWHERE IN THIS CLASS
if (i >= capacity)
return null;
else if(array[i] == null)
{
throw new NoSuchElementException("No such element !");
}
else
{
list.remove(i);
E e = array[i];
array[i] = null;
//size--;
return e;
}
}
public JstyIterator iterator() {
// YOUR CODE ANYWHERE IN THIS CLASS
return new JstyIterator(this);
}
}
JstyIterator.java
package array2;
/*
* An iterator for the class JstyArray. Performs all standard tasks of an iterator.
* Specifically, when calling next() on an invalid iterator, a NoSuchElementException is raised
by this class.
*
*/
import java.util.Iterator;
import java.util.NoSuchElementException;
public class JstyIterator implements Iterator{
private JstyArray array;
private int index;
private int initialSize;
public JstyIterator(JstyArray array) {
this.array = array;
this.index = 0;
this.initialSize = array.list.size();
}
// YOUR CODE ANYWHERE IN THIS CLASS
public boolean hasNext() {
// YOUR CODE ANYWHERE IN THIS CLASS
if (array.size == index)
return false;
else
return true;
}
public E next() throws NoSuchElementException {
// YOUR CODE ANYWHERE IN THIS CLASS
if (initialSize != array.list.size())
throw new NoSuchElementException("Array elements have been modified !");
else if (hasNext()) {
return array.get(index++);
} else {
throw new NoSuchElementException("There are no elements in the array. Size = " +
array.size);
}
}
public void remove() {
// we need this method for the nagging Java compiler
// you may leave empty
}
}
JstTester.java
package array2;
import java.util.NoSuchElementException;
public class JstTester {
static JstyArray array;
public static void main(String[] args) {
array = new JstyArray<>(10);
for(int i=0; i<10; i++)
array.set(i, i);
//Test case - testRemoveBegin4
array.remove(4);
//Test case - testPrintEachNoException
System.out.println(" Test case - testPrintEachNoException");
JstyIterator itr = array.iterator();
while(itr.hasNext())
{
System.out.print(itr.next() + " ");
}
System.out.println("");
//Test case - testRemoveBegin4
array.remove(5);
System.out.println(" Test case - testConsecutiveBad");
itr = array.iterator();
array.remove(1);
try{
while(itr.hasNext())
{
System.out.print(itr.next() + " ");
}}catch (NoSuchElementException e) {
System.out.println("Exception: Error: " + e.getMessage());
}
itr = array.iterator();
System.out.println(" Test case - testConsecutiveGood");
while(itr.hasNext())
{
System.out.print(itr.next() + " ");
}
System.out.println("");
try
{
array.remove(5);
}catch (Exception e) {
System.out.println(" Exception: Error: " + e.getMessage());
}
}
}
OUTPUT:
Test case - testPrintEachNoException
0 1 2 3 null 5 6 7 8 9
Test case - testConsecutiveBad
Exception: Error: Array elements have been modified !
Test case - testConsecutiveGood
0 null 2 3 null null 6 7 8 9
Exception: Error: No such element !

More Related Content

Similar to Array with Iterator. Java styleImplement an array data structure a.pdf

Similar to Array with Iterator. Java styleImplement an array data structure a.pdf (20)

Preparation Data Structures 05 chain linear_list
Preparation Data Structures 05 chain linear_listPreparation Data Structures 05 chain linear_list
Preparation Data Structures 05 chain linear_list
 
Collections
CollectionsCollections
Collections
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
What is an exception in java?
What is an exception in java?What is an exception in java?
What is an exception in java?
 
Java Generics
Java GenericsJava Generics
Java Generics
 
JAVA(UNIT 4)
JAVA(UNIT 4)JAVA(UNIT 4)
JAVA(UNIT 4)
 
Java tut1
Java tut1Java tut1
Java tut1
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
 
Java tut1
Java tut1Java tut1
Java tut1
 
Javatut1
Javatut1 Javatut1
Javatut1
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
PHP 5 Magic Methods
PHP 5 Magic MethodsPHP 5 Magic Methods
PHP 5 Magic Methods
 
Inheritance
InheritanceInheritance
Inheritance
 
Given the code below create a method called, getCollisionCount that .pdf
Given the code below create a method called, getCollisionCount that .pdfGiven the code below create a method called, getCollisionCount that .pdf
Given the code below create a method called, getCollisionCount that .pdf
 
JavaHTP7e_1313_DDP.ppt
JavaHTP7e_1313_DDP.pptJavaHTP7e_1313_DDP.ppt
JavaHTP7e_1313_DDP.ppt
 
----------Evaluator-java---------------- package evaluator- import j.docx
----------Evaluator-java---------------- package evaluator-   import j.docx----------Evaluator-java---------------- package evaluator-   import j.docx
----------Evaluator-java---------------- package evaluator- import j.docx
 

More from fcaindore

You are the CIO of a medium size company tasked with modernizing the.pdf
You are the CIO of a medium size company tasked with modernizing the.pdfYou are the CIO of a medium size company tasked with modernizing the.pdf
You are the CIO of a medium size company tasked with modernizing the.pdffcaindore
 
Why are some goods only provided by the government Why are .pdf
Why are some goods only provided by the government Why are .pdfWhy are some goods only provided by the government Why are .pdf
Why are some goods only provided by the government Why are .pdffcaindore
 
When a supervisor comes to the HR manager to evaluate disciplinary a.pdf
When a supervisor comes to the HR manager to evaluate disciplinary a.pdfWhen a supervisor comes to the HR manager to evaluate disciplinary a.pdf
When a supervisor comes to the HR manager to evaluate disciplinary a.pdffcaindore
 
What is the role of an ethical leader in corporate cultures a. A le.pdf
What is the role of an ethical leader in corporate cultures a. A le.pdfWhat is the role of an ethical leader in corporate cultures a. A le.pdf
What is the role of an ethical leader in corporate cultures a. A le.pdffcaindore
 
What is the main purpose of a project management planSolution.pdf
What is the main purpose of a project management planSolution.pdfWhat is the main purpose of a project management planSolution.pdf
What is the main purpose of a project management planSolution.pdffcaindore
 
What is the difference between a balanace sheet and a net income she.pdf
What is the difference between a balanace sheet and a net income she.pdfWhat is the difference between a balanace sheet and a net income she.pdf
What is the difference between a balanace sheet and a net income she.pdffcaindore
 
What is involved in personalization and codification of tacit to exp.pdf
What is involved in personalization and codification of tacit to exp.pdfWhat is involved in personalization and codification of tacit to exp.pdf
What is involved in personalization and codification of tacit to exp.pdffcaindore
 
What dimensions of quality were highlighted in the Delta Airlines ba.pdf
What dimensions of quality were highlighted in the Delta Airlines ba.pdfWhat dimensions of quality were highlighted in the Delta Airlines ba.pdf
What dimensions of quality were highlighted in the Delta Airlines ba.pdffcaindore
 
What are the similarities and differences between the ETC of Photosy.pdf
What are the similarities and differences between the ETC of Photosy.pdfWhat are the similarities and differences between the ETC of Photosy.pdf
What are the similarities and differences between the ETC of Photosy.pdffcaindore
 
What are non-tax costs of tax planningSolutionFollowings are .pdf
What are non-tax costs of tax planningSolutionFollowings are .pdfWhat are non-tax costs of tax planningSolutionFollowings are .pdf
What are non-tax costs of tax planningSolutionFollowings are .pdffcaindore
 
There is a host of sociological and cultural research that paints a r.pdf
There is a host of sociological and cultural research that paints a r.pdfThere is a host of sociological and cultural research that paints a r.pdf
There is a host of sociological and cultural research that paints a r.pdffcaindore
 
True or False With argument passage by reference, the address of the.pdf
True or False With argument passage by reference, the address of the.pdfTrue or False With argument passage by reference, the address of the.pdf
True or False With argument passage by reference, the address of the.pdffcaindore
 
This is problem is same problem which i submitted on 22017, I just.pdf
This is problem is same problem which i submitted on 22017, I just.pdfThis is problem is same problem which i submitted on 22017, I just.pdf
This is problem is same problem which i submitted on 22017, I just.pdffcaindore
 
SOme of functions of the eukaryotic orgenelles are performed in bact.pdf
SOme of functions of the eukaryotic orgenelles are performed in bact.pdfSOme of functions of the eukaryotic orgenelles are performed in bact.pdf
SOme of functions of the eukaryotic orgenelles are performed in bact.pdffcaindore
 
please explain the global entreprenurship revolution for a flatter w.pdf
please explain the global entreprenurship revolution for a flatter w.pdfplease explain the global entreprenurship revolution for a flatter w.pdf
please explain the global entreprenurship revolution for a flatter w.pdffcaindore
 
ourse O D. growth rate of currency in circulation-growth rate of the .pdf
ourse O D. growth rate of currency in circulation-growth rate of the .pdfourse O D. growth rate of currency in circulation-growth rate of the .pdf
ourse O D. growth rate of currency in circulation-growth rate of the .pdffcaindore
 
Modify the project so tat records are inserted into the random acess.pdf
Modify the project so tat records are inserted into the random acess.pdfModify the project so tat records are inserted into the random acess.pdf
Modify the project so tat records are inserted into the random acess.pdffcaindore
 
Many hospitals have systems in place and are now or will in the futu.pdf
Many hospitals have systems in place and are now or will in the futu.pdfMany hospitals have systems in place and are now or will in the futu.pdf
Many hospitals have systems in place and are now or will in the futu.pdffcaindore
 
List the S + D and the organism that causes a vesicle, Gumma, purule.pdf
List the S + D and the organism that causes a vesicle, Gumma, purule.pdfList the S + D and the organism that causes a vesicle, Gumma, purule.pdf
List the S + D and the organism that causes a vesicle, Gumma, purule.pdffcaindore
 
Let k be the number of ON-state devices in a group of n devices on a .pdf
Let k be the number of ON-state devices in a group of n devices on a .pdfLet k be the number of ON-state devices in a group of n devices on a .pdf
Let k be the number of ON-state devices in a group of n devices on a .pdffcaindore
 

More from fcaindore (20)

You are the CIO of a medium size company tasked with modernizing the.pdf
You are the CIO of a medium size company tasked with modernizing the.pdfYou are the CIO of a medium size company tasked with modernizing the.pdf
You are the CIO of a medium size company tasked with modernizing the.pdf
 
Why are some goods only provided by the government Why are .pdf
Why are some goods only provided by the government Why are .pdfWhy are some goods only provided by the government Why are .pdf
Why are some goods only provided by the government Why are .pdf
 
When a supervisor comes to the HR manager to evaluate disciplinary a.pdf
When a supervisor comes to the HR manager to evaluate disciplinary a.pdfWhen a supervisor comes to the HR manager to evaluate disciplinary a.pdf
When a supervisor comes to the HR manager to evaluate disciplinary a.pdf
 
What is the role of an ethical leader in corporate cultures a. A le.pdf
What is the role of an ethical leader in corporate cultures a. A le.pdfWhat is the role of an ethical leader in corporate cultures a. A le.pdf
What is the role of an ethical leader in corporate cultures a. A le.pdf
 
What is the main purpose of a project management planSolution.pdf
What is the main purpose of a project management planSolution.pdfWhat is the main purpose of a project management planSolution.pdf
What is the main purpose of a project management planSolution.pdf
 
What is the difference between a balanace sheet and a net income she.pdf
What is the difference between a balanace sheet and a net income she.pdfWhat is the difference between a balanace sheet and a net income she.pdf
What is the difference between a balanace sheet and a net income she.pdf
 
What is involved in personalization and codification of tacit to exp.pdf
What is involved in personalization and codification of tacit to exp.pdfWhat is involved in personalization and codification of tacit to exp.pdf
What is involved in personalization and codification of tacit to exp.pdf
 
What dimensions of quality were highlighted in the Delta Airlines ba.pdf
What dimensions of quality were highlighted in the Delta Airlines ba.pdfWhat dimensions of quality were highlighted in the Delta Airlines ba.pdf
What dimensions of quality were highlighted in the Delta Airlines ba.pdf
 
What are the similarities and differences between the ETC of Photosy.pdf
What are the similarities and differences between the ETC of Photosy.pdfWhat are the similarities and differences between the ETC of Photosy.pdf
What are the similarities and differences between the ETC of Photosy.pdf
 
What are non-tax costs of tax planningSolutionFollowings are .pdf
What are non-tax costs of tax planningSolutionFollowings are .pdfWhat are non-tax costs of tax planningSolutionFollowings are .pdf
What are non-tax costs of tax planningSolutionFollowings are .pdf
 
There is a host of sociological and cultural research that paints a r.pdf
There is a host of sociological and cultural research that paints a r.pdfThere is a host of sociological and cultural research that paints a r.pdf
There is a host of sociological and cultural research that paints a r.pdf
 
True or False With argument passage by reference, the address of the.pdf
True or False With argument passage by reference, the address of the.pdfTrue or False With argument passage by reference, the address of the.pdf
True or False With argument passage by reference, the address of the.pdf
 
This is problem is same problem which i submitted on 22017, I just.pdf
This is problem is same problem which i submitted on 22017, I just.pdfThis is problem is same problem which i submitted on 22017, I just.pdf
This is problem is same problem which i submitted on 22017, I just.pdf
 
SOme of functions of the eukaryotic orgenelles are performed in bact.pdf
SOme of functions of the eukaryotic orgenelles are performed in bact.pdfSOme of functions of the eukaryotic orgenelles are performed in bact.pdf
SOme of functions of the eukaryotic orgenelles are performed in bact.pdf
 
please explain the global entreprenurship revolution for a flatter w.pdf
please explain the global entreprenurship revolution for a flatter w.pdfplease explain the global entreprenurship revolution for a flatter w.pdf
please explain the global entreprenurship revolution for a flatter w.pdf
 
ourse O D. growth rate of currency in circulation-growth rate of the .pdf
ourse O D. growth rate of currency in circulation-growth rate of the .pdfourse O D. growth rate of currency in circulation-growth rate of the .pdf
ourse O D. growth rate of currency in circulation-growth rate of the .pdf
 
Modify the project so tat records are inserted into the random acess.pdf
Modify the project so tat records are inserted into the random acess.pdfModify the project so tat records are inserted into the random acess.pdf
Modify the project so tat records are inserted into the random acess.pdf
 
Many hospitals have systems in place and are now or will in the futu.pdf
Many hospitals have systems in place and are now or will in the futu.pdfMany hospitals have systems in place and are now or will in the futu.pdf
Many hospitals have systems in place and are now or will in the futu.pdf
 
List the S + D and the organism that causes a vesicle, Gumma, purule.pdf
List the S + D and the organism that causes a vesicle, Gumma, purule.pdfList the S + D and the organism that causes a vesicle, Gumma, purule.pdf
List the S + D and the organism that causes a vesicle, Gumma, purule.pdf
 
Let k be the number of ON-state devices in a group of n devices on a .pdf
Let k be the number of ON-state devices in a group of n devices on a .pdfLet k be the number of ON-state devices in a group of n devices on a .pdf
Let k be the number of ON-state devices in a group of n devices on a .pdf
 

Recently uploaded

Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 

Recently uploaded (20)

Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 

Array with Iterator. Java styleImplement an array data structure a.pdf

  • 1. Array with Iterator. Java style Implement an array data structure as a class JstyArray to support the Iterable interface such that the following code works: The iterator provided by this class follows the behaviour of typical Java style (Jsty). If the underlying collection is modified, the iterator becomes invalid and an exception is raised. An example of code that may generate an exception is below: There are 4 necessary methods for the Array. get(), set(), remove() and iterator(). There are 2 necessary methods for Iterator. hasNext() and next(). Other than these, you need to create more methods for communicating between Array and the Iterator. Object references are very useful in this scenario. Once you have an iterator going. There is the next step of handling multiple iterators for the same data structure. More than one iterator can exist, at different times. There are iterators which are •are invalid and have raised an exception, or •are invalid and have not yet raised an exception, or •are valid, they were created after modification to the data structure. Multiple iterators are one of the harder tests THERE ARE TWO CLASSES USED as shown below: .................................................................................................................... JstyIterator.java: /* * An iterator for the class JstyArray. Performs all standard tasks of an iterator. * Specifically, when calling next() on an invalid iterator, a NoSuchElementException is raised by this class. * */ import java.util.Iterator; import java.util.NoSuchElementException; public class JstyIterator implements Iterator{ private JstyArray array; private int index;
  • 2. public JstyIterator(JstyArray array) { this.array = array; index = 0; } // YOUR CODE ANYWHERE IN THIS CLASS public boolean hasNext() { // YOUR CODE ANYWHERE IN THIS CLASS if (array.size == index) return false; else return true; } public E next() throws NoSuchElementException { // YOUR CODE ANYWHERE IN THIS CLASS if (array.list.size() != array.size) throw new NoSuchElementException("Array elements have been modified !"); else if (hasNext()) { return array.get(index++); } else {
  • 3. throw new NoSuchElementException("There are no elements in the array. Size = " + array.size); } } public void remove() { // we need this method for the nagging Java compiler // you may leave empty } } .......................................................................................................................................................... JstyArray.java: /* * An array that implements the Iterable interface. * Returns an iterator that would raise an exception if the array was modified (set or remove) * */ import java.util.LinkedList; public class JstyArray implements Iterable{ // YOUR CODE ANYWHERE IN THIS CLASS private E[] array; public static final int CAPACITY = 100; public int size;
  • 4. public int capacity; public LinkedList list; // there could be more instance variables! /* * initialise array with capacity. If capacity is less than 1, use CAPACITY. * */ @SuppressWarnings("unchecked") public JstyArray(int capacity) { // YOUR CODE ANYWHERE IN THIS CLASS if (capacity { array = (E[]) new Object[CAPACITY]; this.capacity = CAPACITY; list = new LinkedList(); size = 0; } else { array = (E[]) new Object[capacity];
  • 5. this.capacity = capacity; list = new LinkedList(); size = 0; } } /* * if index is outside range of array. simply return * */ public void set(int i, E val) { // YOUR CODE ANYWHERE IN THIS CLASS if (i >= capacity) return; else { array[i] = val; list.add(i, val); size++; }
  • 6. } /* * if index is outside range of array. return null * */ public E get(int i) { // YOUR CODE ANYWHERE IN THIS CLASS if (i >= capacity) return null; else return array[i]; } /* * if index is outside range of array. return null * */ public E remove(int i) { // YOUR CODE ANYWHERE IN THIS CLASS if (i >= capacity) return null; else
  • 7. { list.remove(i); E e = array[i]; array[i] = null; return e; } } public JstyIterator iterator() { // YOUR CODE ANYWHERE IN THIS CLASS return new JstyIterator(this); } } ........................................................................................................................................................... .............. It passes some testcase but not all. Can you fix my code for it to pass all testcases TESTCASES testremove Begin4 V testPrintEachNoException testremoveEnd5 V testNested1 testremoveEnd3 V testremove Begin3 X testConsecutiveUseBadGood X testremoveEnd1 X testremoveEnd2 X testremoveEnd4 X testremoveBegin2 X testremove Single X testConsecutiveUseGoodBadGood Solution PROGRAM CODE: JstyArray.java package array2;
  • 8. /* * An array that implements the Iterable interface. * Returns an iterator that would raise an exception if the array was modified (set or remove) * */ import java.util.LinkedList; import java.util.NoSuchElementException; public class JstyArray implements Iterable{ // YOUR CODE ANYWHERE IN THIS CLASS private E[] array; public static final int CAPACITY = 100; public int size; public int capacity; public LinkedList list; // there could be more instance variables! /* * initialise array with capacity. If capacity is less than 1, use CAPACITY. * */ @SuppressWarnings("unchecked") public JstyArray(int capacity) { // YOUR CODE ANYWHERE IN THIS CLASS if (capacity<1) { array = (E[]) new Object[CAPACITY]; this.capacity = CAPACITY; list = new LinkedList(); size = 0; } else { array = (E[]) new Object[capacity]; this.capacity = capacity; list = new LinkedList(); size = 0; }
  • 9. } /* * if index is outside range of array. simply return * */ public void set(int i, E val) { // YOUR CODE ANYWHERE IN THIS CLASS if (i >= capacity) return; else { array[i] = val; list.add(i, val); size++; } } /* * if index is outside range of array. return null * */ public E get(int i) { // YOUR CODE ANYWHERE IN THIS CLASS if (i >= capacity) return null; else return array[i]; } /* * if index is outside range of array. return null * */ public E remove(int i) { // YOUR CODE ANYWHERE IN THIS CLASS if (i >= capacity) return null; else if(array[i] == null)
  • 10. { throw new NoSuchElementException("No such element !"); } else { list.remove(i); E e = array[i]; array[i] = null; //size--; return e; } } public JstyIterator iterator() { // YOUR CODE ANYWHERE IN THIS CLASS return new JstyIterator(this); } } JstyIterator.java package array2; /* * An iterator for the class JstyArray. Performs all standard tasks of an iterator. * Specifically, when calling next() on an invalid iterator, a NoSuchElementException is raised by this class. * */ import java.util.Iterator; import java.util.NoSuchElementException; public class JstyIterator implements Iterator{ private JstyArray array; private int index; private int initialSize; public JstyIterator(JstyArray array) { this.array = array; this.index = 0; this.initialSize = array.list.size(); }
  • 11. // YOUR CODE ANYWHERE IN THIS CLASS public boolean hasNext() { // YOUR CODE ANYWHERE IN THIS CLASS if (array.size == index) return false; else return true; } public E next() throws NoSuchElementException { // YOUR CODE ANYWHERE IN THIS CLASS if (initialSize != array.list.size()) throw new NoSuchElementException("Array elements have been modified !"); else if (hasNext()) { return array.get(index++); } else { throw new NoSuchElementException("There are no elements in the array. Size = " + array.size); } } public void remove() { // we need this method for the nagging Java compiler // you may leave empty } } JstTester.java package array2; import java.util.NoSuchElementException; public class JstTester { static JstyArray array; public static void main(String[] args) { array = new JstyArray<>(10); for(int i=0; i<10; i++) array.set(i, i); //Test case - testRemoveBegin4 array.remove(4);
  • 12. //Test case - testPrintEachNoException System.out.println(" Test case - testPrintEachNoException"); JstyIterator itr = array.iterator(); while(itr.hasNext()) { System.out.print(itr.next() + " "); } System.out.println(""); //Test case - testRemoveBegin4 array.remove(5); System.out.println(" Test case - testConsecutiveBad"); itr = array.iterator(); array.remove(1); try{ while(itr.hasNext()) { System.out.print(itr.next() + " "); }}catch (NoSuchElementException e) { System.out.println("Exception: Error: " + e.getMessage()); } itr = array.iterator(); System.out.println(" Test case - testConsecutiveGood"); while(itr.hasNext()) { System.out.print(itr.next() + " "); } System.out.println(""); try { array.remove(5); }catch (Exception e) {
  • 13. System.out.println(" Exception: Error: " + e.getMessage()); } } } OUTPUT: Test case - testPrintEachNoException 0 1 2 3 null 5 6 7 8 9 Test case - testConsecutiveBad Exception: Error: Array elements have been modified ! Test case - testConsecutiveGood 0 null 2 3 null null 6 7 8 9 Exception: Error: No such element !