NullPointExeption when try to put variable to object in Java - 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>();

Related

Hashmap inside a hashmap with arraylist

Declaration:-
private static HashMap<String, HashMap<String, ArrayList>> parentMap = new HashMap<>();
private static HashMap<String, ArrayList> childMap = new HashMap<>();
How do I want to store data in hashmap?
"India":
"EmployeeName":[A,B,C]
"China":
"EmployeeName":[D,E,F]
Methods used:-
public static ArrayList<String> getMap(String parentkey, String childKey) {
return parentMap.get(parentkey).get(childKey);
}
public static ArrayList<String> setMap(String parentkey, String childKey, String value) {
childMap.computeIfAbsent(childKey, k -> new ArrayList<>()).add(value);
parentMap.put(parentkey, childMap);
return getMap(parentkey, childKey);
}
setMap("India", "EmployeeName", "A")
setMap("India", "EmployeeName", "B")
setMap("India", "EmployeeName", "C")
setMap("China", "EmployeeName", "D")
setMap("China", "EmployeeName", "E")
setMap("China", "EmployeeName", "F")
How data get stored and printed in hashmap while fetchng from getMap method:
System.out.println("India" + getMap("India").get("EmployeeName"));
System.out.println("China" + getMap("China").get("EmployeeName"));
"India" [A,B,C,D,E,F]
"China" [A,B,C,D,E,F]
Whilst i know keeping the childKey name unique would do thejob for me but I wish to keep the same childKey name under each parentkey name and store the respecive value in arraylist.
Any solution to my problem is welcome.
The problem is that you keep reusing the same childMap, regardless of which parentKey is being used. You need to look up the respective child map when adding values.
That means that childMap should be a local variable, nothing more. Delete your private static HashMap<String, ArrayList> childMap.
Try this:
public static ArrayList<String> setMap(String parentkey, String childKey, String value) {
HashMap<String, ArrayList> childMap = parentMap.computeIfAbsent(parentkey, k->new HashMap<>());
childMap.computeIfAbsent(childKey, k -> new ArrayList<>()).add(value);
return getMap(parentkey, childKey);
}
Proof that this works
Suggestion, don't have generic types and dont have static params
private HashMap<String, HashMap<String, ArrayList<String>>> parentMap = new HashMap<>();
private HashMap<String, ArrayList<String>> childMap = new HashMap<>();
Try to replace this method
public ArrayList<String> setMap(String parentkey, String childKey, String value) {
childMap.putIfAbsent(childKey, new ArrayList<>()); // inserts a key only if the key is not already present
childMap.get(childKey).add(value); // puts the value in the existing key and
if (!parentMap.containsKey(parentkey)) { // puts in the parent map only if not present.
parentMap.put(parentkey, childMap);
}
}
Since the childmap is referenced already, No need to put again.
If I was you I will do it in more "OOP way" so that you can benefit from static typing. Something like:
import java.util.List;
class Employee{
String name;
String getName(){
return name;
}
}
public class CompanyBranch{
String national;
List<Employee> employees;
List<String> getEmployeeAllName(){
return employees.stream().map(Employee::getName).toList();
}
}

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<>();

Java Object Scope

I am trying to create an object based on a condition, therefore the object creation is within the conditional's scope, however I need to see the object outside of that scope. I thought adding it to a Map would work, but it doesn't. Consider the following example:
TestModel.java
public class TestModel {
private String text;
public void setText(String text){
this.text = text;}
public String getText(){
return this.text;}
}
ScopeTest.java
import java.util.*;
class ScopeTest {
public static void main(String[] args) {
TestModel testModel;
Map<String, Object> myModel = new HashMap<String, Object>();
for (int i=1; i<2; i++){ // if a certain condition is met, create an object as below
testModel = new TestModel();
testModel.setText("test text");
myModel.put("test", testModel);
}
for (Map.Entry<String, Object> entry : myModel.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
System.out.println("key=" + key); // I can see the key value
System.out.println("value.getText()=" + value.getText()); // but can't see testModel object. I am not sure how to resolve.
}
}
}
cheers,
Geofrey Rainey.
You have to cast the Object value with your Class. Like this.
System.out.println("value.getText()=" + ((TestModel) value).getText());
If you dont want to cast the object then you can use like this.
class ScopeTest {
public static void main(String[] args) {
TestModel testModel;
Map<String, TestModel> myModel = new HashMap<String, TestModel>();//Use TestModel
instead of object
for (int i=1; i<2; i++){
testModel = new TestModel();
testModel.setText("test text");
myModel.put("test", testModel);
}
for (Entry<String, TestModel> entry : myModel.entrySet()) {
String key = entry.getKey();
TestModel value = entry.getValue();
System.out.println("key=" + key);
System.out.println("value.getText()=" + value.getText());
}
}
}
You should cast the Object into your model.
TestModel value = (TestModel) entry.getValue();
I think you might have to cast the object returned by the HashMap to be a TestModel before you can use a method of that class.
Why not just use TestModel as generic type of value in your Map like below?
Map<String, TestModel> myModel = new HashMap<>();
// ^^^^^^^^^ - instead of Object
This way you can iterate over your map with
for (Map.Entry<String, TestModel> entry : myModel.entrySet()) {
...
}
and you will be able to store value in
TestModel value = entry.getValue();
without needing to cast it. Now since type of value reference will be TestModel compiler will let you use its methods like getText() without problems.
System.out.println("value.getText()=" + value.getText());
Also I am not sure why you are using loop if you want to iterate over it once. Simple if would be better. Another thing is using Map to hold one element seems unnecessary. You can just use one reference like
boolean someCondition = true;
TestModel testModel = null;
if (someCondition) { // if a certain condition is met, create
testModel = new TestModel();
testModel.setText("test text");
}
if (testModel!=null){
System.out.println(testModel.getText());
}

I'm getting "Value is not a valid option" for SelectManyCheckBox

I have this code in my JSP page:
<h:selectManyCheckbox id="chb" value="#{MyBean.selectedCheckBoxes}" layout="pageDirection">
<f:selectItems value="#{MyBean.checkBoxItems}"/>
</h:selectManyCheckbox>
And in my MyBean:
public class MyBean {
public MyBean() {
for (Elem section : sections) {
checkBoxItems.put(section.getName(), section.getObjectID());
}
}
private String[] selectedCheckBoxes;
private Map<String, Object> checkBoxItems = new LinkedHashMap<String, Object>();
public String save() {
//save is not being executed....
return FORWARD;
}
public Map<String, Object> getCheckBoxItems() {
return checkBoxItems;
}
public void setCheckBoxItems(Map<String, Object> checkBoxItems) {
this.checkBoxItems = checkBoxItems;
}
public String[] getSelectedCheckBoxes() {
return selectedCheckBoxes;
}
public void setSelectedCheckBoxes(String[] selectedCheckBoxes) {
this.selectedCheckBoxes = selectedCheckBoxes;
}
}
When I click save it is giving the below message in <t:message for="chb"/>
"chb": Value is not a valid option.
Even though I did not add the required attribute for h:selectManyCheckbox, it is trying to validate or doing something else...
I've changed checkBoxItems variable type(with getter/setters) to List<SelectItem>, but it is not working as well.
What can be the reason, how can I solve it?
PS: I'm using JSF 1.1
You will get this error when the equals() test on a selected item has not returned true for any of the available items. So, when roughly the following happens under JSF's covers:
boolean valid = false;
for (Object availableItem : availableItems) {
if (selectedItem.equals(availableItem)) {
valid = true;
break;
}
}
if (!valid) {
// Validation error: Value is not valid!
}
That can in your particular case only mean that section.getObjectID() does not return a String which is what your selectedCheckboxes is declared to, but a different type or a custom type where equals() is not implemented or broken.
Update as per your comment, the getObjectID() returns Integer. It's thus been treated as String because selectedCheckBoxes is declared as String[]. You should change the following
private String[] selectedCheckBoxes;
private Map<String, Object> checkBoxItems = new LinkedHashMap<String, Object>();
to
private Integer[] selectedCheckBoxes;
private Map<String, Integer> checkBoxItems = new LinkedHashMap<String, Integer>();
and maybe (not sure, can't tell from top of head now) also explicitly supply a converter:
<h:selectManyCheckbox ... converter="javax.faces.Integer">
i didnt find any problem in th code, i thought there is the problem the list u passed to oneManyCheckBox.
hardcode some values in list in getter than check
public Map<String, Object> getCheckBoxItems() {
checkBoxItems.clear();
checkBoxItems.put("aaaa", "aaaa");
checkBoxItems.put("bbbb", "bbbb");
checkBoxItems.put("cccc", "cccc");
checkBoxItems.put("dddd", "dddd");
checkBoxItems.put("eeee", "eeee");
return checkBoxItems;
}

Categories