java.lang.NullPointerException Error [duplicate] - java

This question already has answers here:
Why are my fields initialized to null or to the default value of zero when I've declared and initialized them in my class' constructor?
(4 answers)
Closed 6 years ago.
I am a beginner with Java .. & I keep getting this error .. java.lang.NullPointerException pointing to this line --> Double hOption = healthBenDesig.get("employeeOnly");
Can someone tell me if i am missing something or what exactly I am doing wrong please?
private HashMap<String, Double> healthBenDesig;
public VariableList()
{
HashMap<String, Double> healthBenDesig = new HashMap<String, Double>();
}
public VariableList()
{
HashMap<String, Double> healthBenDesig = new HashMap<String, Double>();
}
public void getHMP()
{
Double hOption = healthBenDesig.get("employeeOnly");
System.out.println("The health Option you chose is: " + hOption);
}
public HashMap setHealthOpt()
{
healthBenDesig.put("none", 0.00);
healthBenDesig.put("employeeOnly", 311.87);
healthBenDesig.put("spouse", 592.56);
healthBenDesig.put("children", 717.30);
healthBenDesig.put("kids", 882.60);
System.out.println(healthBenDesig);
return healthBenDesig;
}

You're shadowing the healthBenDesig by re-declaring it in your constructors leaving the class field null. Don't re-declare it.
Change
public VariableList() {
HashMap<String, Double> healthBenDesig = new HashMap<String, Double>();
}
to:
public VariableList() {
healthBenDesig = new HashMap<String, Double>();
}

You are not intializing your class member healthBenDesig instead you are shadowing it using the lcoal variable. This is causing healthBenDesig as un-initialized and leading to NullPointerException. your In your constructor, change it from
public VariableList()
{
// re-declaration or shadowing of memeber variable healthBenDesig
HashMap<String, Double> healthBenDesig = new HashMap<String, Double>();
}
to
public VariableList()
{
healthBenDesig = new HashMap<String, Double>();
}

You are able to initialize healthBenDesig at property declare
private HashMap<String, Double> healthBenDesig = new HashMap<String, Double>();

Related

Not an "unsafe operation" error: Incompatible types Object cannot be converted to Entry<String, Boolean>

I have a Map in a class where I store a String key and a boolean value. Then, I return the map from the function getMap().
public class FacilityMachines {
private static Map<String, Boolean> map = new HashMap<String, Boolean>();
public Map getMap(){
return map;
}
In the class below, I'm trying to fetch that map, and then save it to an external file, I also instantiate FacilityMachines there:
public class WriteFile {
FacilityMachines fm = new FacilityMachines();
private Map<String, Boolean> m = new HashMap<String, Boolean>();
}
In WriteFile, I'm trying to parse the map into a new HashMap:
public void saveFacilityInfo() {
for (Map.Entry<String, Boolean> j: fm.getMap().entrySet()){
String s = j.getKey();
boolean b = j.getValue();
oStream.println(i + ": " + s + " = " + b + ". ");
}
}
oStream is just the variable for my PrintWriter.
The above yields Object cannot be converted to Entry<String, Boolean> error.
If I change the method signature of saveFacilityInfo to saveFacilityInfo(FacilityMachines fm), and then use the fm variable to try to fetch the map at the line for (Map.Entry<String, Boolean> j: fm.getMap().entrySet()) then I get a cannot find symbol on all the functions from the Entry interface: entrySet(), getKey(), and getValue().
And before anyone asks, I've imported HashMap and Map, and also tried using only import java.util.*; to import everything just in case.
I've also tried extending FacilityMachines from WriteFile and got the same results.
You need to return the map on the FacilityMachines class getMap() method with the correct type
public class FacilityMachines {
private static Map<String, Boolean> map = new HashMap<String, Boolean>();
public Map<String, Boolean> getMap(){
return map;
}
}

How can I get Map getters values

I create Details class and that class create Map object. and set getters setters.
setdatavalues class I set values to the setters
Then I try to get that values in getdatavalues class. by calling getters methord.
problem is I cannot get values in that getters. display empty array.
In getdatavalues calss I create mymap object and assign getMyMap() method and display the values
public class Details{
private Map<String, String> myMap = new LinkedHashMap<String, String>();
public Details() {
super();
}
public Map<String, String> getMyMap() {
return myMap;
}
public void setMyMap(Map<String, String> myMap) {
this.myMap = myMap;
}
}
public static void setdatavalues(){
LinkedHashMap<String, String> myMap=new LinkedHashMap<String, String>();
ArrayList<String> fields,values=new ArrayList<String>();
Details details= new Details();
|
|
fields=readNumbers();
values=readStrings();
for(int j=0;j<fields.size();j++)
{
myMap.put(fields.get(j),values.get(j));
}
details.setMyMap(myMap);
}
}
public static void getdatavalues(){
Details details= new Details();
//System.out.println(details.getMyMap().values());
Map<String,String> mymap = details.getMyMap();
System.out.println(mymap.values());
}
output
details that is set values is setdatavalues is thrown away and new empty details is used in getdatavalues. You must pass the Details object that is set data to where data in Details object is printed to print the data set.

How to create a hashmap in java class

This is my code. My intention is create a hashmap with 4 values, then export this class as a jar, add it to another project, and use the hashmap values there.
I'm getting error in all the "hmap.put". I'm unable to understand what I'm doing wrong. Please help.
import java.util.HashMap;
public class MyFirstClass {
private HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(2, "Jane");
hmap.put(4, "John");
hmap.put(3, "Klay");
hmap.put(1, "Deena");
public HashMap<Integer, String> gethmap()
{
return this.hmap;
}
public void sethmap(HashMap hmap)
{
this.hmap = hmap;
}
}
import java.util.HashMap;
public class MyFirstClass {
private HashMap<Integer, String> hmap = new HashMap<Integer, String>() {
{
hmap.put(4, "John");
hmap.put(3, "Klay");
hmap.put(1, "Deena");
}
};
public HashMap<Integer, String> gethmap() {
return this.hmap;
}
public void sethmap(HashMap<Integer, String> hmap) {
this.hmap = hmap;
}
}
Above code will help you to get the result which you desire. You should also note that you can not use instance variable directly inside class. you have to use that inside method only.
Java doesn't allow executing any statements outside of the scope of any method, field initialization or static block - that's why you get an error.
I suppose, your intent is to do some initialization with that four lines. And Java has support for such kind of initialization - it is the class constructor. So the proper code would look like the following:
import java.util.HashMap;
public class MyFirstClass {
private HashMap<Integer, String> hmap = new HashMap<Integer, String>();
// this is a constructor
public MyFirstClass() {
hmap.put(2, "Jane");
hmap.put(4, "John");
hmap.put(3, "Klay");
hmap.put(1, "Deena");
}
// here goes your other code
}
This way every object of MyFirstClass you create using new MyFirstClass() will contain the data you put in the constructor.
You can read more about the constructors in Java in the official documentation: https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
There are multiple ways to do this. Easiest one is to just add brackets to your put statements:
import java.util.HashMap;
public class MyFirstClass {
private HashMap<Integer, String> hmap = new HashMap<Integer, String>();
{
hmap.put(2, "Jane");
hmap.put(4, "John");
hmap.put(3, "Klay");
hmap.put(1, "Deena");
}
public HashMap<Integer, String> gethmap() {
return this.hmap;
}
public void sethmap(HashMap hmap) {
this.hmap = hmap;
}
}
You should add a constructor to your class:
public MyFirstClass() {
this.hmap = new HashMap<Integer,String>();
// you can do .put here if you wish
}
And change the hmap field to:
private HashMap<Integer, String> hmap;
You're using a method outside of a method. You cannot call Hashmap.put within the class but outside the method - as was mentioned you want to do that in the constructor of the class
public class MyFirstClass {
public MyFirstClass() { //put it here }
}
You can put it in a static block, just as:
private static final Map<Integer, String> NAME_MAP = new HashMap<Integer, String>() {
private static final long serialVersionUID = 1L;
{
NAME_MAP.put(2, "Jane");
NAME_MAP.put(4, "John");
NAME_MAP.put(3, "Klay");
NAME_MAP.put(1, "Deena");
}
};

Cannot instantiate Map<String, ? extends Object> map = new TreeMap<String, ? extends Object>();

I am trying to create a TreeMap with a generic type but I am unable to. I am doing this because my map can like these:
Map<String, QueryTerm> terms = new TreeMap<String, QueryTerm>();
Map<String, String> params = new TreeMap<String, String>();
So instead of creating multiple functions to handle the maps with different types I want to create one which both types.
How can I do this and what am I doing wrong?
Function:
private Map<String, ? extends Object> setDatumMap(UserSession session, String parameterName)
{
Map<String, ? extends Object> map = new TreeMap<String, ? extends Object>();
//Get comma delimited list of filter keys. Split them and use them to retrieve associated values.
String sFilters = (String) session.getAttribute(parameterName);
String[] filterList = sFilters.split(",");
for(String filterName : filterList)
{
String filterValue = (String) session.getAttribute(filterName);
if (filterValue != null && !filterValue.isEmpty())
{
filter.put(filterName, setQueryTermList(filterValue, ListType.BOOLEAN_LIST));
}
}
return filter;
}
You should simply instantiate the map like so:
Map<String, Object> map = new TreeMap<String, Object>();
You can't instantiate using a wildcard, and it's not necessary unless you expect that the compiler will cast to the appropriate class by guessing what value you are going to get. We didn't get there yet.
you need to change you this line :
private Map<String, ? extends Object> setDatumMap(UserSession session, String parameterName)
{
Map<String, ? extends Object> map = new TreeMap<String, ? extends Object>();
//rest of your code
To
private Map<String, Object> setDatumMap(UserSession session, String parameterName)
{
Map<String, Object> map = new TreeMap<String, Object>();
//rest of your code.
This will work.

why is nullpointerexception thrown in this code in Java?

I am unable to trace through why null pointer exception is thrown here, I am sure it is pretty simple, but somehow I am missing it. It is thrown when the checkoutBook method is called. Any help here?
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Library {
HashMap<String, List<String>> checkoutBooks;
Library() {
HashMap<String, List<String>> checkoutBooks = new HashMap<String, List<String>>();
}
public void checkoutBook(String isbn, String patron) {
if (checkoutBooks.containsKey(isbn)) {
checkoutBooks.get(isbn).add(patron);
} else {
List<String> patronlist = new ArrayList<String>();
patronlist.add(patron);
checkoutBooks.put(isbn, patronlist);
System.out.println("hello");
}
}
public static void main(String[] args){
Library library = new Library();
library.checkoutBook("000", "Cay Horstman");
library.checkoutBook("000", "Sharron Morrow");
}
}
Because you didn't assign any value to this variable:
HashMap<String, List<String>> checkoutBooks;
You just defined new one in constructor. So remove that instance checkoutBooks variable, or do this:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Library {
HashMap<String, List<String>> checkoutBooks;
Library() {
checkoutBooks = new HashMap<String, List<String>>();
}
public void checkoutBook(String isbn, String patron) {
if (checkoutBooks.containsKey(isbn)) {
checkoutBooks.get(isbn).add(patron);
} else {
List<String> patronlist = new ArrayList<String>();
patronlist.add(patron);
checkoutBooks.put(isbn, patronlist);
System.out.println("hello");
}
}
public static void main(String[] args){
Library library = new Library();
library.checkoutBook("000", "Cay Horstman");
library.checkoutBook("000", "Sharron Morrow");
}
}
Because you didn't initialize the field checkoutBooks in the constructor. You initialized a local variable with the same name. Change your constructor to this:
HashMap<String, List<String>> checkoutBooks;
Sandbox() {
checkoutBooks = new HashMap<String, List<String>>();
}
In the Library constructor, you declare a local variable named checkoutBooks, and initialize it, but you don't initialize the same-named field at class level. Some suggestions:
At a minimum, to fix the error, change the constructor to do assignment only rather than declaring a new variable:
Library() {
checkoutBooks = new HashMap<String, List<String>>();
}
Since you're not reassigning the checkoutBooks field after construction, you can declare the field final. Then it will catch this sort of error immediately at compile time, because final fields are required to be initialized. It also prevents accidental reassignment of the field later, which enhances robustness.
class Library {
final HashMap<String, List<String>> checkoutBooks;
...
Since you don't do anything else in the constructor, you can inline the initialization directly into the field declaration:
class Library {
final HashMap<String, List<String>> checkoutBooks = new HashMap<String, List<String>>();
// no constructor
...
As of Java 7, you can avoid repeating the type arguments by using <>:
class Library {
final HashMap<String, List<String>> checkoutBooks = new HashMap<>();
checkoutBooks.containsKey
is null when you used HashMap<String, List<String>> checkoutBooks = new HashMap<String, List<String>>(); inside constructor, thats why getting Exception
class Library {
HashMap<String, List<String>> checkoutBooks;
Library() {
checkoutBooks = new HashMap<String, List<String>>(); // just change here
}
public void checkoutBook(String isbn, String patron) {
if (checkoutBooks.containsKey(isbn)) {
checkoutBooks.get(isbn).add(patron);
} else {
List<String> patronlist = new ArrayList<String>();
patronlist.add(patron);
checkoutBooks.put(isbn, patronlist);
System.out.println("hello");
}
}
public static void main(String[] args){
Library library = new Library();
library.checkoutBook("000", "Cay Horstman");
library.checkoutBook("000", "Sharron Morrow");
}
}

Categories

Resources