NullPointerException when checking null - java

Basically, I create a map to store a unique key and a list of items. at first the map is null so in my class dosomething im checking if the map is null but it returns an exception. Please see code below.
Does anyone know what i can do to fix this issue?
public class MyClass{
private static Map<String, List<MyList>> MyMap = null;
private static void doSomething(){
String myKey = "hello";
if(MyMap.get(myKey) == null ){ // Here is where i got the exception "java.lang.NullPointerException"
//do something
}
}
}
public class MyList{
// do my List
}

private static Map<String, List<MyList>> MyMap = null; // null here and not initialized
MyMap.get(myKey)
your MyMap is null so it is throwing NPE

Your MyMap is null. Do as below..
public class MyClass{
private static Map<String, List<MyList>> MyMap = new HashMap<String, List<MyList>>(); // creating instance
private static void doSomething(){
String myKey = "hello";
if(MyMap.get(myKey) == null ){ // Here is where i got the exception "java.lang.NullPointerException"
//do something
}
}
}
public class MyList{
// do my List
}

Your MyMap is throwing the NullPointerException. This happens because you've explicitly set it to null:
private static Map<String, List<MyList>> MyMap = null;
Instead you should initialise MyMap first:
private static Map<String, List<MyList>> MyMap = new HashMap<String, List<MyList>>();

you have to initialize your HasMap.
Map<String, List<String>> myMap = new HashMap<String, List<String>>();
if(myMap.get("bla") == null){
//do somethig
}

Related

How to check String equality while iterating over two lists?

I have two java classes:
public class MyClass1 {
private String userId;
private String userName;
private List<CustomList1> customList1;
// getters and setters
// inner CustomList1 class
}
public class MyClass2 {
private String userId;
private List<CustomList2> customList2;
// getters and setters
// inner CustomList2 class
}
Now, I have have lists of these classes:
List<MyClass1> classOneList;
List<MyClass2> classTwoList;
In both classOneList and classTwoList lists, object should be sorted with userId ascending. userId in both lists should have same values. What I want to check is that:
Has both lists same size? If not, thow error exception about.
Has every next element from both list the same userId? If not, throw another exception.
Step 1. I have done with simply if statement.
By prototype, step 2. should look like this:
for (el1, el2 : classOneList, classTwoList) {
el1.getUserId().isEqualTo(el2.getUserId());
}
Try the below code for your problem.
public class Testing {
public static void main(String[] args) {
Map<String, List<String>> map1 = new LinkedHashMap<String, List<String>>();
List<String> m1l1 = new LinkedList<String>();
m1l1.add("One");
m1l1.add("Two");
m1l1.add("Three");
m1l1.add("Four");
map1.put("1", m1l1);
List<String> m1l2 = new LinkedList<String>();
m1l2.add("One");
m1l2.add("Two");
m1l2.add("Three");
m1l2.add("Four");
map1.put("2", m1l2);
// Add more element into the map1 by creating more list.
Map<String, List<String>> map2 = new LinkedHashMap<String, List<String>>();
List<String> m2l1 = new LinkedList<String>();
m2l1.add("One");
m2l1.add("Two");
m2l1.add("Three");
m2l1.add("Four");
map2.put("1", m2l1);
// Add more element into the map2 by creating more list.
for (Entry<String, List<String>> entry : map1.entrySet()) {
if (map2.containsKey(entry.getKey())) {
if (entry.getValue().size() == map2.get(entry.getKey()).size()) {
} else {
System.out.println("UserId are same but list are different for userid: " + entry.getKey());
}
}
else {
System.out.println("Userid '"+entry.getKey()+"' exists in map1 but is not found in map2");
}
}
}
}
Hope this may help you.
if(classOneList.size() != classTwoList.size()){
throw new ErrorException();
}else{
classOneList = classOneList.stream().sorted(Comparator.comparing(MyClass1::getUserId)).collect(Collectors.toList());
classTwoList = classTwoList.stream().sorted(Comparator.comparing(MyClass2::getUserId)).collect(Collectors.toList());
for (int i = 0; i < classOneList.size(); i++){
if(!classOneList.get(i).getUserId().equals(classTwoList.get(i).getUserId())){
throw new AnotherErrorException();
}
}
}

Null pointer exception when trying assign values to hashmap

package com.assignment;
import java.util.ArrayList;
import java.util.HashMap;
public class Interview {
private HashMap<String,Integer> stateCounts = null;
private HashMap<String,String> stateNames;
private ArrayList<InputData> inputList = null;
public void loadStateNames(String stateKey,String stateName)
{
stateNames.put(stateKey, stateName);
}
public static void main(String Args[])
{
Interview interview = new Interview();
interview.loadStateNames("NY", "New York");
}
}
When I try to pass to strings to loadStateNames. I get a null pointer exception. Can't figure out whats causing this error.
Exception in thread "main" java.lang.NullPointerException
at com.assignment.Interview.loadStateNames(Interview.java:41)
at com.assignment.Interview.main(Interview.java:57)
You have not initialised the Map ,change it to ::
private HashMap<String,String> stateNames = new HashMap<String,String>();
You forgot to initialize your HashMap, change:
private HashMap<String,String> stateNames;
to:
private HashMap<String,String> stateNames = new HashMap<String,String>();
You are not initializing them. You should do this in the constructor:
public Inteview() {
stateNames = new HashMap<>();
}
Also, I doubt you want to give a null reference to stateCounts and inputList. They should also be initialized in the constructor:
public Inteview() {
stateNames = new HashMap<>();
stateCounts = new HasMap<>();
inputList = new ArrayList<>();
}
When you declare a class variable like this:
private HashMap<String,String> stateNames;
or like this:
private HashMap<String,String> stateNames = null;
it is initialized with null.
You cannot add keys/values to it when it is null.
Either initialize it in a constructor or at declaration time.
private HashMap<String,String> stateNames = new HashMap<String,String>()
You should create an instance:
private HashMap<String,String> stateNames = new HashMap<String, String>();
And for others too. BTW use interface in left side for polymorphism and in Java 7+ you don't need provide types in right side:
private Map<String,String> stateNames = new HashMap<>();

NullPointExeption when try to put variable to object in Java

I create object which contain feature geometry and attributes:
public class Feature {
Feature(String wkt) {
this.wkt = wkt;
}
private HashMap<Column, String> columnMap;
private String wkt;
public String getWKT() {
return wkt;
}
public void addAttribute(Column column, String value) {
columnMap.put(column, value);
}
public String getAttribute(String column) {
return columnMap.get(column) ;
}
public Map<Column, String> getAttributes(){
return columnMap;
}
}
Wkt is a geometry. ColumnMap is object contain a attributes as HashMap:
public class Column {
private String columnName;
Column(String columnName) {
this.columnName = columnName;
}
public String getName() {
return columnName;
}
}
Now i says:
columnList = new ArrayList<Column>(columns);
......
Feature feature= new Feature(WKT);
for(int p=0;p<columnList.size();p++){
for(int k=0;k<=ViewObject.getMIDInfo(totalObjects).length;k++){
if(p==k){
System.out.println("Column "+columnList.get(p).getName()+" Value "+ ViewObject.getMIDInfo(totalObjects)[k].toString());
//feature.addAttribute(columnList.get(p), ViewObject.getMIDInfo(totalObjects)[k].toString());
}
}
}
And get output:
Column id Value 22
Column kadnumm Value "66-41-0707001-19"
So how i understand columnList and ViewObject.getMIDInfo(totalObjects) is not empty. After this i change :
//feature.addAttribute(columnList.get(p), ViewObject.getMIDInfo(totalObjects)[k].toString());
to:
feature.addAttribute(columnList.get(p), ViewObject.getMIDInfo(totalObjects)[k].toString());
And get exeption:
Column id Value 22
java.lang.NullPointerException
at objects.Feature.addAttribute(Feature.java:18)
at objects.MIFParser.findRegion(MIFParser.java:181)
at objects.MIFParser.instanceNextObject(MIFParser.java:66)
at Read.main(Read.java:40)
How i understand NullPointerException means that i try to use empty objects? Whats wrong?
P.s. Sorry my english can be terrible especially with title .
UPDATE
Okey i add this: this.columnMap = new HashMap<Column, String>(); in FEature class constructor.
But now i try to do:
System.out.println(feature.getAttribute("id")+" "+feature.getAttribute("kadnumm"));
and output:
null null
What can be wrong?
You didnt initialize your columnMap:
private HashMap<Column, String> columnMap = new HashMap<Column, String>();
addAttribute tries to put something on columnMap, but you don't create columnMap anywhere. You need to add to your Feature constructor:
Feature(String wkt) {
this.wkt = wkt;
this.columnMap = new HashMap<Column, String>(); // <=== The new bit
}
...or add an initialization to your declaration:
private HashMap<Column, String> columnMap = new HashMap<Column, String>();
// The new bit--- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Just declaring the member isn't sufficient, the member just refers to an object, and starts off null. You need to create the object for it to refer to and assign that object to it.
columnMap object is not initialized when you create a new instance of Feature. So it is null when you call columnMap.put(column, value); in addAttribute
instead of
private HashMap<Column, String> columnMap;
do
private HashMap<Column, String> columnMap = new HashMap<Column, String>();
You must initialize the map:
private HashMap<Column, String> columnMap = new HashMap<Column, String>();

NULL pointer using hashmap

Can someone please tell my why I'm getting a null pointer exception with this code? In my Nutrition class, I implement a hash map:
public class Nutrition implements Serializable{
private final String TAG = Nutrition.class.getSimpleName();
//class variables
...
//hash map declaration
HashMap<String, String> nutrition;
public Nutrition(JSONObject jo) throws JSONException{
//create hash map
this.nutrition = new HashMap<String, String>();
//place data in hashmap
this.serving_size = jo.optString("serving_size");
nutrition.put("serving_size", serving_size);
Log.i(TAG, serving_size + " : Serving Size");
....
}
//method to get hashmap
public HashMap<String, String> getHashMap(){
return nutrition;
}
Then in another class, I call getHashMap() and I get a null pointer:
//nutrition item
Nutrition nutritionInfo = dish.getNutrition();
nutInfo = nutritionInfo.getHashMap();
Can someone tell me what I'm doing wrong and how I can fix it?
The second line will throw an NPE if dish.getNutrition() returns null.
Nutrition nutritionInfo = dish.getNutrition();
nutInfo = nutritionInfo.getHashMap();
Since you haven't shown us the code in the Dish class, I would assume it occurs here.

Returning an unmodifiable map

Using Collections.unmodifiableMap(...), I'm trying to return an unmodifiable view of a map. Let's say I have the following method,
public final Map<Foo, Bar> getMap(){
...
return Collections.unmodifiableMap(map);
}
Why is it legal elsewhere to do the following,
Map<Foo, Bar> map = getMap();
map.put(...);
This doesn't throw an UnsupportedOperationException like I thought it would. Can someone please explain this, or suggest how I can successfully return a truly unmodifiable map?
Are you sure you're not masking your exceptions somehow? This works absolutely fine, in that it throws UnsupportedOperationException:
import java.util.*;
public class Test {
public static void main(String[] args) {
Map<String, String> map = getMap();
map.put("a", "b");
}
public static final Map<String, String> getMap(){
Map<String, String> map = new HashMap<String, String>();
map.put("x", "y");
return Collections.unmodifiableMap(map);
}
}
I suggest you print out map.getClass() on the return value of the method - I would expect it to be an UnmodifiableMap.
I created a small test program and my program threw an 'UnsupportedOperationException' when I tried to put data in.
code:
import java.util.*;
public class TestUnmodifiableMap
{
Map<Integer, String> myMap;
public TestUnmodifiableMap()
{
myMap = new HashMap<Integer, String>();
}
public final Map<Integer, String> getMap()
{
return Collections.unmodifiableMap(myMap);
}
public static void main(String[] args)
{
TestUnmodifiableMap t = new TestUnmodifiableMap();
Map<Integer, String> testMap = t.getMap();
testMap.put(new Integer("1"), "Hello");
}
}
What else are you doing in your class?
There must be something else wrong. There's no way you can put something in that map after you wrapped it as an unmodifiable map.
I would also suggest to return
return Collections.<Foo, Bar>unmodifiableMap(map);
otherwise you will get "unchecked" warnings when compiling your code with -Xlint:unchecked.

Categories