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<>();
Related
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();
}
}
}
I really do not understand why I am getting this compile error after the parentheses for "Map<String, Integer> buildTable(){".
Here is the code I am working on: I already have the city class defined.
import java.util.Map;
import java.util.HashMap;
public class CityMap{
public static void main(String[] args){
String _city;
Map<String, Integer> cityTable = buildTable();
Map<String, Integer> buildTable(){
String aCity;
Map<String, Command> result = new HashMap<String, Command>();
aCity = new City();
result.put("NYC", 100000);
aCity = new City();
result.put("Boston", 500);
return result;
}
I am a beginner, so any explanation is welcome.
You cannot declare methods inside of other methods.
Move your buildTable method outside of the main method (and then you have to either make it static or create an object instance to call it from main).
Your method declaration for buildTable needs to live outside of your method declaration for main.
I.E.,
import java.util.Map;
import java.util.HashMap;
public class CityMap{
public static void main(String[] args)
{
String _city;
Map<String, Integer> cityTable = buildTable();
}
public static Map<String, Integer> buildTable(){
String aCity;
Map<String, Command> result = new HashMap<String, Command>();
aCity = new City();
result.put("NYC", 100000);
aCity = new City();
result.put("Boston", 500);
return result;
}
}
import java.util.Map;
import java.util.HashMap;
public class CityMap {
static Map < String, Integer > buildTable() {
Map < String, Integer > result = new HashMap < String, Integer > ();
result.put("NYC", 100000);
result.put("Boston", 500);
return result;
}
public static void main(String[] args) {
Map < String, Integer > cityTable = buildTable();
}
}
Command is not defined, creating instance variables not to use them will do nothing at all, method can not be declared inside method; only inside class - you can declare class inside method (inner class) and method inside that class.
public static void main(String[] args){} is a method, after all. For this reason you cannot declare another method inside it.
Also, your compiler gets confused when you return result because although it is intended for your buildTable() method, it is placed inside your main() method.
Solution:
public static void main(String[] args){
String _city;
Map<String, Integer> cityTable = buildTable();
}
Map<String, Integer> buildTable(){
String aCity;
Map<String, Command> result = new HashMap<String, Command>();
aCity = new City();
result.put("NYC", 100000);
aCity = new City();
result.put("Boston", 500);
return result;
}
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
}
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>();
public class MapData {
ArrayList<String> Redsp = new ArrayList<String>();
ArrayList<String> Bluesp = new ArrayList<String>();
ArrayList<String> Playersp = new ArrayList<String>();
public MapData(ArrayList<String> redsp, ArrayList<String> bluesp, ArrayList<String> playersp) {
Redsp = redsp;
Bluesp = bluesp;
Playersp = playersp;
}
}
How do I make a object of MapData, and add/remove items to/from the object?
I would like to add like 6 items to bluesp and redsp, and 20 to playersp.
MapData TEST = new MapData(null,null,null);
TEST.??
I would create some more methods to MapData
For example to add to Bluesp
public void addToBlueSp(String string) {
Bluesp.add(string);
}
Also I would use camelCase as this is the standard thing to do in Java.
I would probably recommend creating the ArrayLists inside the ctor too as there is little point passing them into an object and then using that object to add/remove items from them. If you have the ArrayList you could add them outside of this object. But that is a design thing...
The easiest way is to provide getters for the three collections and then manipulate them the ordinary way. Such manipulations will take effect on the member fields:
public class MapData {
ArrayList<String> Redsp = new ArrayList<String>();
ArrayList<String> Bluesp = new ArrayList<String>();
ArrayList<String> Playersp = new ArrayList<String>();
public MapData(ArrayList<String> redsp, ArrayList<String> bluesp, ArrayList<String> playersp) {
Redsp = redsp;
Bluesp = bluesp;
Playersp = playersp;
}
public ArrayList<String> getRedsp();
}
And then you do:
MapData TEST = new MapData(null,null,null);
TEST.getRedsp().add("Text1");
TEST.getRedsp().add("Text2");
and so on.
However, take care: you construct not with empty lists, but with null and my code will trigger NPE. Consider setting the default values to empty lists.
Use add() and remove() methods
- You can opt for creating the adding and removing methods Or make all the ArrayList as static
Eg:
public void addToRedSp(String string) {
Redsp.add(string);
}
public void remToRedSp(String string) {
Redsp.remove(string);
}
MapData TEST = new MapData(null,null,null);
// To add
test.addToRedSp("Vivek");
// To remove
test.remToRedSp(0); // or MapData.Redsp.remove("Vivek");
- ArrayList as static
public static ArrayList<String> Redsp = new ArrayList<String>();
public static ArrayList<String> Bluesp = new ArrayList<String>();
public static ArrayList<String> Playersp = new ArrayList<String>();
MapData TEST = new MapData(null,null,null);
// To add
MapData.Redsp.add("Vivek");
// To remove
MapData.Redsp.remove(0); // or MapData.Redsp.remove("Vivek");
You can either add getter and setter methods for the Lists to MapData and add new elements like this:
TEST.getRedsp().add("hello");
with
public ArrayList<String> getRedsp()
{
if(Redsp == null)
Redsp = new ArrayList<String>();
return Redsp;
}
or you can introduce an add method for each list to MapData:
TEST.addToRedsp("hello");
with
public boolean addToRedsp(String value)
{
if(Redsp == null)
Redsp = new ArrayList<String>();
return Redsp.add(value)
}
Proceed similarly for the delete case.
By the way: Have a look at variable naming conventions.