How to add to array in main?

82 views Asked by At

I have created an array which I wanted to control from main. My code runs, but I don't know how to add integers to the array from the main class. Also as each ConcreteSubject has its own storage array, how would i change this to store them all in the same array?

public class ConcreteSubject extends AbstractSpy
{
    private AbstractSpy[] spies = new AbstractSpy[10];
    private int i = 0;

    public void addSpy(AbstractSpy s) {
        if (i < spies.length) {
            spies[i] = s;
            System.out.println("spy added at index " + i);
            i++;
        }
    }
}

public class TestClass
{
    public static void main(String[] args) {
        ConcreteSubject cs = new ConcreteSubject();
        AbstractSpy spies = new AbstractSpy() {
            @Override
            public void addSpy(AbstractSpy spies) {
            }
        };

        cs.addSpy(cs);
        spies.addSpy(spies);
    }
}
1

There are 1 answers

2
spork On BEST ANSWER

It seems like your program logic is a little borked. This bit in particular doesn't make much sense:

        ***AbstractSpy spies = new AbstractSpy() {
            @Override
            public void addSpy(AbstractSpy spies) {
            }
        };

        cs.addSpy(cs);
        ***spies.addSpy(spies);

What you're doing is creating TWO AbstractSpy instances, one named cs and one named spies. On that last line you're adding spies to itself! That doesn't help you at all.

Note that AbstractSpy is the most granular unit in your setup - it shouldn't have an addSpy() method and its own internal array, it should be the thing that's added to something else's array!

Here's the same code, but cleaned up a bit:

public abstract class AbstractSpy { }
public class ConcreteSpy extends AbstractSpy { }

public class ConcreteSubject {
    private AbstractSpy[] spies = new AbstractSpy[10];
    private int i = 0;

    public void addSpy(AbstractSpy spy) {
        if (i < spies.length)
        {
            spies[i] = spy;
            System.out.println("spy added at index " + i);
            i++;
        }
    }
}

public class TestClass {
    public static void main(String[] args) {
        ConcreteSubject cs = new ConcreteSubject();
        AbstractSpy spy = new ConcreteSpy();
        cs.addSpy(spy);
    }
}

The big difference here is that ConcreteSpy is an implementation of AbstractSpy that you can add to your ConcreteSubject's array of spies. I think you might have been confused by Java's insistence that you can't create an instance of an abstract class on its own unless you supply an anonymous class that inherits from the abstract class.