-2

I have an static ArrayList which I can only access from a class ("Sale"). In that ArrayList I want to add items of the same class. How can I add them from the constructor?

I've done it this way and it doesn't work:

public class Sale{
     private static ArrayList<Sale> sales;
     private Buyer buyer;
     private Item item;

     public Sale(Buyer buyer, Item item){
          this.buyer=buyer;
          this.item=item;
          sales.add(this);
     }
.....

Thanks in advance, I'm starting programming in Java.

jari
  • 23
  • 6
  • 1
    Why would you want even to do that recursively. You do not need that. Since the variable is static, you can easily created a method and add the `Collection` there. I do not see any value in having this logic, when you can have a for loop and add the values there, through the static method, which references the static variable `sales`. – Jernej K Mar 11 '16 at 18:42
  • 2
    I would also ask: why do you want to do this? In the sense of: this smells like BAD design. Why should the Sale class ... maintain a list of Sales?! If your "shopping system" needs to keep lists of Sales objects; then heck; they should be in other places. – GhostCat Mar 11 '16 at 18:43
  • Agreeing with @Jägermeister, that is BAD practice. – Jernej K Mar 11 '16 at 18:44
  • I know this solution is quite awful, but I was asked to do so (it is an exercise). Thanks for the comments. – jari Mar 11 '16 at 18:53
  • 2
    Are you _sure_ you understood the exercise? An exercise is supposed to teach correct principles, and this is all wrong. As an exercise it is recommending very bad practice. – Jim Garrison Mar 11 '16 at 18:57
  • Yes, I am _sure_. Thank you for your concern. I know it is not a good solution, but professors at university ... – jari Mar 11 '16 at 19:42

1 Answers1

3

You haven't initialized your sales ArrayList. You can do so by changing

private static ArrayList<Sale> sales;

to something like

private static ArrayList<Sale> sales = new ArrayList<Sale>();

or using the diamond operator <> (Java 7+) like

private static ArrayList<Sale> sales = new ArrayList<>();

But I would suggest you program to the List interface. Something like

private static List<Sale> sales = new ArrayList<>();

Another possible option is a static initializer, like

private static List<Sale> sales;
static {
    sales = new ArrayList<>();
}
Community
  • 1
  • 1
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249