-1

I have this code

public class TupleSpace implements aTupleSpace {
private Collection<aTuple> theSpace;
public TupleSpace() { 
    theSpace
}

public void out(aTuple v) {
    theSpace.add(v);}

the .add causes an error, I think its either because .add is not defined for a generic collection type? or because im not properly understanding the line:

private Collection<aTuple> theSpace;

i have to keep this line the same but can make any changes to the out method or the rest of the class

I just want to be able to add things to a collection and search the collection for them

R-4
  • 75
  • 4
  • 2
    Is `aTuple` a class? If so, that should be fine - although your constructor body is broken. `Collection` has an `add(E)` method, so your `out` method is fine. (I'd strongly advise you to start following Java naming conventions though...) – Jon Skeet Mar 07 '16 at 15:18
  • null pointer exception – R-4 Mar 07 '16 at 15:21
  • @R-4 you need to instanciate your collection in your TupleSpace constructor. `theSpace = new ArrayList();` – neomega Mar 07 '16 at 15:22

1 Answers1

2

A Collection is just an Interface.

It defines what you can do with theSpace and is somewhat independent of what theSpace actually is. It may be a List or a Map or something entirely different.

Collection.add(E e) is indeed a method that is common to all Collections. Still the actual implementation might differ.

However, private Collection<aTuple> theSpace; is just declaring the variable. It will be set to null when you create an instance of TupleSpace. This is the reason for the NullPointerException that is thrown when you try to use theSpace.

Hence, you will need to create a concrete Collection instance and assign it to theSpace before you can use it (e.g. add objects).

There are plenty of Collection types that come ready to use with the SDK. Choose one that fits your use case. Here is an example, using an ArrayList:

// ...
public TupleSpace() { 
    this.theSpace = new ArrayList<aTuple>();
}
// ...
lupz
  • 3,620
  • 2
  • 27
  • 43