开发者

Java issues with ArrayList

I have a class that contains two arraylists which I'm trying to store objects into, one for each object type. In my main class, I'm inserting the objects like so:

 for (int i =0; i < 3; i++)
 {
     Cat cat = new Cat("meow",i);
     Dog dog = new Dog("woof",i);
     objList.addCat(cat);
   开发者_开发百科  objList.addDog(dog);
 }

My ObjectList (objList) class is setup like:

import java.util.ArrayList;

public class ObjectList {
    public ArrayList  cats;
    public ArrayList  dogs;

    public ObjectList()
    {
        this.cats   = new ArrayList();
        this.dogs   = new ArrayList();
    }

    public void addCat(Cat c)
    {
        this.cats.add(c);
    }

    public void addDog(Dog d)
    {
        this.dogs.add(d);
    }
}

I get a java.lang.NullPointerException starting at the objList.addCat(cat); line however. I printed out the cat objects properties right before this line, and both values seem to be set. I tried to see if I could just pass an int to my addCat arrayList, but I got the same error, so I assume I'm using arraylist within my class incorrectly. Is there an error in my code that's readily apparent?


Couple of things I'd suggest:

  1. Don't make your fields public;
  2. Use interfaces where possible (List instead of ArrayList);
  3. Favour immutability or at least make your data members final if you're not going to change them; and
  4. (unrelated to this) adopt Java code conventions.

So try this:

public class ObjectList {
  private final List cats;
  private final List dogs; 

  public ObjectList() {   
    cats = new ArrayList();
    dogs = new ArrayList();
  }

  public void addCat(Cat c) {
    cats.add(c);
  }

  public void addDog(Dog d) {
    dogs.add(d);
  }
}

This should avoid any external changes that might be happening. Or, better yet, use generics:

public class ObjectList {
  private final List<Cat> cats;
  private final List<Dog> dogs; 

  public ObjectList() {   
    cats = new ArrayList<Cat>();
    dogs = new ArrayList<Dog>();
  }

  public void addCat(Cat c) {
    cats.add(c);
  }

  public void addDog(Dog d) {
    dogs.add(d);
  }
}

And you are initializing your object list instance right?

ObjectList objList = new ObjectList();
for (int i=0; i<3; i++)  {
  Cat cat = new Cat("meow",i);
  Dog dog = new Dog("woof",i);
  objList.addCat(cat);
  objList.addDog(dog);
}


Did you initialize your objList before using it?

ObjectList objList = new ObjectList();

(before doing your loop)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜