Implementing an iterator for an arraylist
I have a list of instance DynamicArray
which is pretty much an arraylist,
and here I'm trying to implement an iterator:
The problem is I'm not allowed to add any fields so no index field... and I'm trying to write the method next()
for my iterator to return the next prime number, and I thought maybe it'd be a good idea to add it to the array as well.
But every time I'd call next it'll set num to 2 and then it won't increment so ultimately it'll only return 2..
import java.util.Iterator;
public class PrimeIterator implements Iterator<Integer> {
private List<Integer> primes;
//Complete the following method
public PrimeIterator(){
this.primes = new DynamicArray<Integer>();
}
//Complete the following method
public boolean hasNext(){
return false;
}
//Complete the following method
public Integer next(){
Integer num = new Integer(2);
while(!isPrime(num)){
num++;
}
primes.add(num);
return num;
}
public boolean isPrime (Integer num){
for(int i = 2; i*i<=num; i++){
if(num%i == 0) return false;
}
return true;
}
//DO NOT REMOVE OR CHANGE THIS MEHTOD – IT IS REQUIRED
public void remove() {
return;
}
}
Is there any way to fix this? or any idea of how to use the field I got to do that?
java iterator
|
show 1 more comment
I have a list of instance DynamicArray
which is pretty much an arraylist,
and here I'm trying to implement an iterator:
The problem is I'm not allowed to add any fields so no index field... and I'm trying to write the method next()
for my iterator to return the next prime number, and I thought maybe it'd be a good idea to add it to the array as well.
But every time I'd call next it'll set num to 2 and then it won't increment so ultimately it'll only return 2..
import java.util.Iterator;
public class PrimeIterator implements Iterator<Integer> {
private List<Integer> primes;
//Complete the following method
public PrimeIterator(){
this.primes = new DynamicArray<Integer>();
}
//Complete the following method
public boolean hasNext(){
return false;
}
//Complete the following method
public Integer next(){
Integer num = new Integer(2);
while(!isPrime(num)){
num++;
}
primes.add(num);
return num;
}
public boolean isPrime (Integer num){
for(int i = 2; i*i<=num; i++){
if(num%i == 0) return false;
}
return true;
}
//DO NOT REMOVE OR CHANGE THIS MEHTOD – IT IS REQUIRED
public void remove() {
return;
}
}
Is there any way to fix this? or any idea of how to use the field I got to do that?
java iterator
1
Which part is your homework and which part did you write?
– nicomp
Jan 2 at 12:57
I added the isPrime method , and I did write the next method but obviously it doesn't work properly.. My homework is to implement this iterator for this list of primes. However , next() should only return one prime number at a time, and I should do that using the primes field.. so it's not really like iterating over an array.
– lidor718
Jan 2 at 13:00
are you allowed to access values that are already stored within the list?
– L.Spillner
Jan 2 at 13:01
Yes the only prohibition is adding fields
– lidor718
Jan 2 at 13:06
Do you mean that you're not allowed to add fields to theDynamicArray
or to the iterator?
– chrylis
Jan 2 at 13:20
|
show 1 more comment
I have a list of instance DynamicArray
which is pretty much an arraylist,
and here I'm trying to implement an iterator:
The problem is I'm not allowed to add any fields so no index field... and I'm trying to write the method next()
for my iterator to return the next prime number, and I thought maybe it'd be a good idea to add it to the array as well.
But every time I'd call next it'll set num to 2 and then it won't increment so ultimately it'll only return 2..
import java.util.Iterator;
public class PrimeIterator implements Iterator<Integer> {
private List<Integer> primes;
//Complete the following method
public PrimeIterator(){
this.primes = new DynamicArray<Integer>();
}
//Complete the following method
public boolean hasNext(){
return false;
}
//Complete the following method
public Integer next(){
Integer num = new Integer(2);
while(!isPrime(num)){
num++;
}
primes.add(num);
return num;
}
public boolean isPrime (Integer num){
for(int i = 2; i*i<=num; i++){
if(num%i == 0) return false;
}
return true;
}
//DO NOT REMOVE OR CHANGE THIS MEHTOD – IT IS REQUIRED
public void remove() {
return;
}
}
Is there any way to fix this? or any idea of how to use the field I got to do that?
java iterator
I have a list of instance DynamicArray
which is pretty much an arraylist,
and here I'm trying to implement an iterator:
The problem is I'm not allowed to add any fields so no index field... and I'm trying to write the method next()
for my iterator to return the next prime number, and I thought maybe it'd be a good idea to add it to the array as well.
But every time I'd call next it'll set num to 2 and then it won't increment so ultimately it'll only return 2..
import java.util.Iterator;
public class PrimeIterator implements Iterator<Integer> {
private List<Integer> primes;
//Complete the following method
public PrimeIterator(){
this.primes = new DynamicArray<Integer>();
}
//Complete the following method
public boolean hasNext(){
return false;
}
//Complete the following method
public Integer next(){
Integer num = new Integer(2);
while(!isPrime(num)){
num++;
}
primes.add(num);
return num;
}
public boolean isPrime (Integer num){
for(int i = 2; i*i<=num; i++){
if(num%i == 0) return false;
}
return true;
}
//DO NOT REMOVE OR CHANGE THIS MEHTOD – IT IS REQUIRED
public void remove() {
return;
}
}
Is there any way to fix this? or any idea of how to use the field I got to do that?
java iterator
java iterator
edited Jan 2 at 14:01
Sebastien Kerroue
13214
13214
asked Jan 2 at 12:52
lidor718lidor718
315
315
1
Which part is your homework and which part did you write?
– nicomp
Jan 2 at 12:57
I added the isPrime method , and I did write the next method but obviously it doesn't work properly.. My homework is to implement this iterator for this list of primes. However , next() should only return one prime number at a time, and I should do that using the primes field.. so it's not really like iterating over an array.
– lidor718
Jan 2 at 13:00
are you allowed to access values that are already stored within the list?
– L.Spillner
Jan 2 at 13:01
Yes the only prohibition is adding fields
– lidor718
Jan 2 at 13:06
Do you mean that you're not allowed to add fields to theDynamicArray
or to the iterator?
– chrylis
Jan 2 at 13:20
|
show 1 more comment
1
Which part is your homework and which part did you write?
– nicomp
Jan 2 at 12:57
I added the isPrime method , and I did write the next method but obviously it doesn't work properly.. My homework is to implement this iterator for this list of primes. However , next() should only return one prime number at a time, and I should do that using the primes field.. so it's not really like iterating over an array.
– lidor718
Jan 2 at 13:00
are you allowed to access values that are already stored within the list?
– L.Spillner
Jan 2 at 13:01
Yes the only prohibition is adding fields
– lidor718
Jan 2 at 13:06
Do you mean that you're not allowed to add fields to theDynamicArray
or to the iterator?
– chrylis
Jan 2 at 13:20
1
1
Which part is your homework and which part did you write?
– nicomp
Jan 2 at 12:57
Which part is your homework and which part did you write?
– nicomp
Jan 2 at 12:57
I added the isPrime method , and I did write the next method but obviously it doesn't work properly.. My homework is to implement this iterator for this list of primes. However , next() should only return one prime number at a time, and I should do that using the primes field.. so it's not really like iterating over an array.
– lidor718
Jan 2 at 13:00
I added the isPrime method , and I did write the next method but obviously it doesn't work properly.. My homework is to implement this iterator for this list of primes. However , next() should only return one prime number at a time, and I should do that using the primes field.. so it's not really like iterating over an array.
– lidor718
Jan 2 at 13:00
are you allowed to access values that are already stored within the list?
– L.Spillner
Jan 2 at 13:01
are you allowed to access values that are already stored within the list?
– L.Spillner
Jan 2 at 13:01
Yes the only prohibition is adding fields
– lidor718
Jan 2 at 13:06
Yes the only prohibition is adding fields
– lidor718
Jan 2 at 13:06
Do you mean that you're not allowed to add fields to the
DynamicArray
or to the iterator?– chrylis
Jan 2 at 13:20
Do you mean that you're not allowed to add fields to the
DynamicArray
or to the iterator?– chrylis
Jan 2 at 13:20
|
show 1 more comment
1 Answer
1
active
oldest
votes
As far as I understood the question the main issue is with the initialization of the incrementing value, which is reset to 2 on every call of next()
.
To solve such an issue you could access the last entry of the list by simply calling primes.get(primes.size() - 1)
. Of course this could cause an IndexOutOfBoundsException
if it is empty so you have to do a little check before like:
Integer num = primes.isEmpty() ? Integer.valueOf( 1 ) : primes.get( primes.size() - 1 );
num++;
Also note that the returned number should be the last prime number so we have to increment it once before following the rest of the routine. Otherwise the same value would be returned and you would've gained absolutely nothing.
In fact we could easily resolve the problem of increment once by converting the while-loop into a do-while-loop:
public Integer next()
{
int num = primes.isEmpty() ? 1 : primes.get( primes.size() - 1 ).intValue();
do
{
num++;
}
while ( !isPrime( num ) );
Integer primer = Integer.valueOf( num );
primes.add( primer);
return primer;
}
what does int num = primes.isEmpty() ? 1 : primes.get( primes.size() - 1 ).intValue(); mean? can you write it in a more old fashioned way?
– lidor718
Jan 2 at 14:26
it's a conditional expression (well-know as ternary operator) and is like a very short form for if() { }else{ }. If the condition infront of the?
is true then the left expression ( 1 in this case ) will be assigned to the variable. If not the left expression is assigned. In short this particular line assigns either the last item from the list to the number or 1 if the list is empty and no prime numbers have been added yet.
– L.Spillner
Jan 2 at 14:30
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54006742%2fimplementing-an-iterator-for-an-arraylist%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
As far as I understood the question the main issue is with the initialization of the incrementing value, which is reset to 2 on every call of next()
.
To solve such an issue you could access the last entry of the list by simply calling primes.get(primes.size() - 1)
. Of course this could cause an IndexOutOfBoundsException
if it is empty so you have to do a little check before like:
Integer num = primes.isEmpty() ? Integer.valueOf( 1 ) : primes.get( primes.size() - 1 );
num++;
Also note that the returned number should be the last prime number so we have to increment it once before following the rest of the routine. Otherwise the same value would be returned and you would've gained absolutely nothing.
In fact we could easily resolve the problem of increment once by converting the while-loop into a do-while-loop:
public Integer next()
{
int num = primes.isEmpty() ? 1 : primes.get( primes.size() - 1 ).intValue();
do
{
num++;
}
while ( !isPrime( num ) );
Integer primer = Integer.valueOf( num );
primes.add( primer);
return primer;
}
what does int num = primes.isEmpty() ? 1 : primes.get( primes.size() - 1 ).intValue(); mean? can you write it in a more old fashioned way?
– lidor718
Jan 2 at 14:26
it's a conditional expression (well-know as ternary operator) and is like a very short form for if() { }else{ }. If the condition infront of the?
is true then the left expression ( 1 in this case ) will be assigned to the variable. If not the left expression is assigned. In short this particular line assigns either the last item from the list to the number or 1 if the list is empty and no prime numbers have been added yet.
– L.Spillner
Jan 2 at 14:30
add a comment |
As far as I understood the question the main issue is with the initialization of the incrementing value, which is reset to 2 on every call of next()
.
To solve such an issue you could access the last entry of the list by simply calling primes.get(primes.size() - 1)
. Of course this could cause an IndexOutOfBoundsException
if it is empty so you have to do a little check before like:
Integer num = primes.isEmpty() ? Integer.valueOf( 1 ) : primes.get( primes.size() - 1 );
num++;
Also note that the returned number should be the last prime number so we have to increment it once before following the rest of the routine. Otherwise the same value would be returned and you would've gained absolutely nothing.
In fact we could easily resolve the problem of increment once by converting the while-loop into a do-while-loop:
public Integer next()
{
int num = primes.isEmpty() ? 1 : primes.get( primes.size() - 1 ).intValue();
do
{
num++;
}
while ( !isPrime( num ) );
Integer primer = Integer.valueOf( num );
primes.add( primer);
return primer;
}
what does int num = primes.isEmpty() ? 1 : primes.get( primes.size() - 1 ).intValue(); mean? can you write it in a more old fashioned way?
– lidor718
Jan 2 at 14:26
it's a conditional expression (well-know as ternary operator) and is like a very short form for if() { }else{ }. If the condition infront of the?
is true then the left expression ( 1 in this case ) will be assigned to the variable. If not the left expression is assigned. In short this particular line assigns either the last item from the list to the number or 1 if the list is empty and no prime numbers have been added yet.
– L.Spillner
Jan 2 at 14:30
add a comment |
As far as I understood the question the main issue is with the initialization of the incrementing value, which is reset to 2 on every call of next()
.
To solve such an issue you could access the last entry of the list by simply calling primes.get(primes.size() - 1)
. Of course this could cause an IndexOutOfBoundsException
if it is empty so you have to do a little check before like:
Integer num = primes.isEmpty() ? Integer.valueOf( 1 ) : primes.get( primes.size() - 1 );
num++;
Also note that the returned number should be the last prime number so we have to increment it once before following the rest of the routine. Otherwise the same value would be returned and you would've gained absolutely nothing.
In fact we could easily resolve the problem of increment once by converting the while-loop into a do-while-loop:
public Integer next()
{
int num = primes.isEmpty() ? 1 : primes.get( primes.size() - 1 ).intValue();
do
{
num++;
}
while ( !isPrime( num ) );
Integer primer = Integer.valueOf( num );
primes.add( primer);
return primer;
}
As far as I understood the question the main issue is with the initialization of the incrementing value, which is reset to 2 on every call of next()
.
To solve such an issue you could access the last entry of the list by simply calling primes.get(primes.size() - 1)
. Of course this could cause an IndexOutOfBoundsException
if it is empty so you have to do a little check before like:
Integer num = primes.isEmpty() ? Integer.valueOf( 1 ) : primes.get( primes.size() - 1 );
num++;
Also note that the returned number should be the last prime number so we have to increment it once before following the rest of the routine. Otherwise the same value would be returned and you would've gained absolutely nothing.
In fact we could easily resolve the problem of increment once by converting the while-loop into a do-while-loop:
public Integer next()
{
int num = primes.isEmpty() ? 1 : primes.get( primes.size() - 1 ).intValue();
do
{
num++;
}
while ( !isPrime( num ) );
Integer primer = Integer.valueOf( num );
primes.add( primer);
return primer;
}
edited Jan 2 at 14:09
answered Jan 2 at 13:08
L.SpillnerL.Spillner
1,353417
1,353417
what does int num = primes.isEmpty() ? 1 : primes.get( primes.size() - 1 ).intValue(); mean? can you write it in a more old fashioned way?
– lidor718
Jan 2 at 14:26
it's a conditional expression (well-know as ternary operator) and is like a very short form for if() { }else{ }. If the condition infront of the?
is true then the left expression ( 1 in this case ) will be assigned to the variable. If not the left expression is assigned. In short this particular line assigns either the last item from the list to the number or 1 if the list is empty and no prime numbers have been added yet.
– L.Spillner
Jan 2 at 14:30
add a comment |
what does int num = primes.isEmpty() ? 1 : primes.get( primes.size() - 1 ).intValue(); mean? can you write it in a more old fashioned way?
– lidor718
Jan 2 at 14:26
it's a conditional expression (well-know as ternary operator) and is like a very short form for if() { }else{ }. If the condition infront of the?
is true then the left expression ( 1 in this case ) will be assigned to the variable. If not the left expression is assigned. In short this particular line assigns either the last item from the list to the number or 1 if the list is empty and no prime numbers have been added yet.
– L.Spillner
Jan 2 at 14:30
what does int num = primes.isEmpty() ? 1 : primes.get( primes.size() - 1 ).intValue(); mean? can you write it in a more old fashioned way?
– lidor718
Jan 2 at 14:26
what does int num = primes.isEmpty() ? 1 : primes.get( primes.size() - 1 ).intValue(); mean? can you write it in a more old fashioned way?
– lidor718
Jan 2 at 14:26
it's a conditional expression (well-know as ternary operator) and is like a very short form for if() { }else{ }. If the condition infront of the
?
is true then the left expression ( 1 in this case ) will be assigned to the variable. If not the left expression is assigned. In short this particular line assigns either the last item from the list to the number or 1 if the list is empty and no prime numbers have been added yet.– L.Spillner
Jan 2 at 14:30
it's a conditional expression (well-know as ternary operator) and is like a very short form for if() { }else{ }. If the condition infront of the
?
is true then the left expression ( 1 in this case ) will be assigned to the variable. If not the left expression is assigned. In short this particular line assigns either the last item from the list to the number or 1 if the list is empty and no prime numbers have been added yet.– L.Spillner
Jan 2 at 14:30
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54006742%2fimplementing-an-iterator-for-an-arraylist%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Which part is your homework and which part did you write?
– nicomp
Jan 2 at 12:57
I added the isPrime method , and I did write the next method but obviously it doesn't work properly.. My homework is to implement this iterator for this list of primes. However , next() should only return one prime number at a time, and I should do that using the primes field.. so it's not really like iterating over an array.
– lidor718
Jan 2 at 13:00
are you allowed to access values that are already stored within the list?
– L.Spillner
Jan 2 at 13:01
Yes the only prohibition is adding fields
– lidor718
Jan 2 at 13:06
Do you mean that you're not allowed to add fields to the
DynamicArray
or to the iterator?– chrylis
Jan 2 at 13:20