0

I have the following map:

Map<City, Integer> map = getMap();

and my class City:

public class City {
    private String c1;
    private String c2;

    public City(String c1, String c2){
        this.c1 = c1;
        this.c2 = c2;
    }

Now I have a map full of values, and I need to look for a specific key, for example :"London, Paris". My main approach is this one:

map.get(new City("London", "Paris"));

For some reason, it is giving me

Exception in thread "main" java.lang.NullPointerException

and I'm almost sure I cannot do this way.

1
  • 1
    Can you post the whole stack trace? And have you debugged to verify that map isn't null at that point? Commented Nov 7, 2012 at 16:04

4 Answers 4

2

Implement the hashCode and equals methods for the City class, otherwise map.get(new City("London", "Paris")); will always return null.

Sign up to request clarification or add additional context in comments.

Comments

1

You are probably getting the nullpointer when you try to use the result. For this to work you also need to implement the equals and hashcode methods of city.

Comments

0

There're a couple of reasons as to why you might experience a NullPointerException:

  • Your map is null. So when you do a map.get() it throws you the exception
  • Since you've not overriden the equals() and hashCode() method, when you do a get(), the map doesn't return you the correct object, it returns a null instead. When you try to work with this, well, you get the exception.

Comments

0

You need to override hashCode and equals, if you are going to use your class in a hash map:

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((c1 == null) ? 0 : c1.hashCode());
        result = prime * result + ((c2 == null) ? 0 : c2.hashCode());
        return result;
    }

The implementation of equals should be trivial.

Your code fails because you do not define for the compiler how to compare two City objects. You can define comparison rules by overriding the equals function. Whenever you override the equals function, you should also override the hashCode function. The hashCode function is used by a hash map to store key-value pairs in a meaningful and optimal way. The hashCode function is also used when performing a look-up in a hash map.

You can find more copious and more accurate information on these semantics in the following article: http://www.ibm.com/developerworks/java/library/j-jtp05273/index.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.