Question

I'm writing the following code purely for fun and there are probably still errors or it may not even work at all:

public class PrimeGenerator implements PrimitiveIterator.OfInt {
    private final static IntNode HEAD_NODE = new IntNode(2); //error here

    private IntNode lastNode = HEAD_NODE;
    private int current = 0;

    @Override
    public boolean hasNext() {
        return true;
    }
    @Override
    public int nextInt() {
        if (lastNode.value == current) {
            lastNode = lastNode.next;
            return lastNode.value;
        }
        while (true) {
            current++;
            if (isPrime(current)) {
                break;
            }
        }
        appendNode(current);
        return current;
    }

    private boolean isPrime(final int number) {
        PrimeGenerator primeGenerator = new PrimeGenerator();
        int prime = 0;
        while (prime < number) {
            prime = primeGenerator.nextInt();
            if (number % prime == 0) {
                return false;
            }
        }
        return true;
    }

    private void appendNode(final int value) {
        couple(lastNode, new IntNode(value));
    }

    private void couple(final IntNode first, final IntNode second) {
        first.next = second;
        second.previous = first;
    } 

    private class IntNode {
        public final int value;

        public IntNode previous;
        public IntNode next;

        public IntNode(final int value) {
            this.value = value;
        }
    }
}

For people not known with Java 8, don't worry, PrimitiveIterator.OfInt, works the same as Iterator<Integer>.

The issue I am having is on the second line, namely the:

private final static IntNode HEAD_NODE = new IntNode(2);

I get the warning: non-static variable this cannot be referenced from a static class.

I have searched and it should be able to be fixed by making IntNode non-dependant on PrimeGenerator, by moving it in its own public class.

However, what can I do if I do not want IntNode to be publicly known?

Was it helpful?

Solution

You should make your IntNode class static.

If you don't, this means that an IntNode instance cannot exist without an instance of the enclosing class already existing.

In short, you cannot write (provided IntNode was public of course):

new PrimeGenerator.IntNode(whatever);

but you'd have to create a new PrimeGenerator, say generator below, and write:

generator.new IntNode(whatever);

Here however you try and create an IntNode as a class variable for PrimeGenerator. This won't work, since you don't have an instance of PrimeGenerator yet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top