0

I have a files of zipcode, cities, and states. I need to create a class to store these items. The objects will be stored in a binary search tree so I need only one entry per city, state combination. Since some cities have multiple zipcodes, I have been asked to store the zip codes in a list within the class.

basic structure:

public class Places(String city, String state, String zip){
  . . . 
}

I believe I need to create the LinkedList within the class and then add the zip too it, but when I do so I am getting a null pointer exception.

//create new LinkedList in Place
      LinkedList<String> zips = new LinkedList<String>();
      zips.add(zip);

I have found plenty of information about adding objects to lists, but not using lists within objects.

Jen H
  • 1
  • Needs more code! I can't see how the above code causes a `NullPointerException`. This might help: http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it – markspace Nov 24 '15 at 02:55
  • 3
    The code snippet you show should _not_ be causing a `NullPointerException`. You must be doing something else. – Tim Biegeleisen Nov 24 '15 at 02:55
  • Could it be that `zip` is null? Can you post the stacktrace? – dave Nov 24 '15 at 02:55
  • @dave that won't raise a `NullPointerException`. – Luiggi Mendoza Nov 24 '15 at 03:10
  • @LuiggiMendoza okay - `add()` *can* raise a `NullPointerException`. I take it `ArrayList` allows `null` elements so it won't in this case. – dave Nov 24 '15 at 03:17
  • @dave nope, it won't. It will assign `null` as data to the node and continue working with no problem. `List#add` using JDK implementations of `List` won't raise a `NullPointerException`. – Luiggi Mendoza Nov 24 '15 at 03:20
  • Please [edit] your post to contain a [mcve]. Without it, we can only guess what's really going on. (As a bonus, the effort itself might lead you to an answer.) – Kevin J. Chase Nov 24 '15 at 04:09

1 Answers1

0

This should work:

 public class LocationData{
     //Somewhere in your code initiate it, maybe in constructor?
     public LinkedList<String> zips=new LinkedList<String>();
     //do the rest of what this class needs to do
  }

In another class that uses LocationData:

  public class TestClass {
      //or any other method for that matter
      public static void main(String[] args) {
         LocationData ld=new LocationData();
         ld.zips.add("12345"); //adds zipcode of "12345"
        }
   }

The only way a NullPointerException could be raised is if ld or zips is uninitialized. I can't tell exactly where your exception is being raised since you didn't post a complete section of your code.

deepmindz
  • 598
  • 1
  • 6
  • 14
  • Thanks all for your comments. So, there were zips in the file with a null value so the linked list was throwing a null pointer exception. I changed it to an array list and it worked fine. Thanks, Jen – Jen H Nov 25 '15 at 12:16