views:

302

answers:

5

I'm writing two classes to handle simple auctions. I have a class ready and working, which handles the operations for a single auction, and now I'm writing another class like an auction house, to keep track of all the auctions available. When testing the following part of the class:

import java.util.ArrayList;

public class AuctionHouse {
    private ArrayList<DutchAuction> huutokaupat;

    public AuctionHouse() {
    }

    public void addAuction(DutchAuction newAuction) {
     huutokaupat.add(newAuction);
    }
}

inside a main method with following code("kauppa" is a tested and working object-variable):

AuctionHouse talo = new AuctionHouse();
talo.addAuction(kauppa);

I get:

Exception in thread "main" java.lang.NullPointerException at ope.auction.dutch.AuctionHouse.addAuction(AuctionHouse.java:13) at ope.auction.dutch.DutchAuctionTest.main(DutchAuctionTest.java:54)

How can I fix the problem?

+5  A: 

You never actually created the ArrayList. You need

private ArrayList huutokaupat = new ArrayList();
Paul Tomblin
+4  A: 

Your array list is not initialised when you are adding to it. Initialise it in your constructors, or better yet, on the field:

private ArrayList huutokaupat = new ArrayList();
xcut
+1  A: 

huutokaupat is not initialized?

Ben James
A: 

Add to the constructor:

public AuctionHouse() {
     huutokaupat = new ArrayList();
}

This will create an ArrayList object which is referenced from the huutokaupat variable.

nalo
+5  A: 

Everyone has mentioned the Java 1.4 way of creating the list. In Java 5 and up, the proper way to instantiate a collection will include the generic type as well:

ArrayList<DutchAuction> huutokaupat = new ArrayList<DutchAuction>();

Additionally, unless you need to use features specific to an ArrayList, it is better to define huutokaupat using an interface instead of the implementation. For example:

List<DutchAuction> huutokaupat = new ArrayList<DutchAuction>();

if you only need to use List interface methods, or even

Collection<DutchAuction> huutokaupat = new ArrayList<DutchAuction>();

if you only need Collection methods. Using an interface like List or Collection to define the variable type makes it possible to switch the implementation (ArrayList) with something else in the future, and making this switch have minimal effects on your code.

Kaleb Brasee