I'm trying to use a HashMap to store instances of a simple class, called User. I'm using Integer as the key type, as I want to look up entries by user id, but I keep getting NullPointerException when I try to save a new entry.
Here's the snippet of code that's causing the problem:
Integer i = Integer.valueOf(id);
User bob = new User(id, seq, packet.getPort(), packet.getAddress());
if (i == null || bob == null) {
System.out.println("Null object.");
}
users.put(i, bob);
The values used in the User constructor have already been set, and the debug statement I added is never printed. Nevertheless, an exception is thrown when I try to call users.put(i, bob);. Is there another way to use an int as a key?
Edit: I'm dumb and didn't initialize the HashMap itself.
I would guess that users (your HashMap) is null
Related
I am reading a database and filling up a hashtable, my key is a string for example "1-1", which is a string and it is unique (I checked many times) and my value is an object that has other objects as attributes. The problem is that when I am filling my hashtable, some of my entries end up with wrong values for one of the attributes namely MethodTrace.Method.Owner.DeveloperGold.
The value is set correctly in the first iteration but when I reprint the same value in the next iteration or at the end of the loop, I end up with the wrong value
System.out.println("WE ARW IN THE LOOP "+methodtraceHashMap.get("1-1"));
For some reason, it feels like the last value that was set in
MethodTrace.Method.Owner.DeveloperGold = myresults.getString("ownergold");
gets assigned and put into the value in the hashmap corresponding to the entry with the key "1-1". I am not really sure how to fix this.
ResultSet myresults = st.executeQuery("SELECT traces.* from traces");
while (myresults.next()) {
MethodTrace MethodTrace = new MethodTrace();
Method method= new Method();
Requirement requirement= new Requirement();
requirement=RequirementHashMap.get(myresults.getString("requirementid"));
method =
MethodHashMap.get(myresults.getString("methodid"));
MethodTrace.setMethod(method);
MethodTrace.setRequirement(requirement);
//checking whether the method is present in the
// superclasses
MethodTrace.setGold(myresults.getString("goldfinal"));
String reqMethod=MethodTrace.Requirement.ID+"-
"+MethodTrace.Method.ID;
String reqClass=MethodTrace.Requirement.ID+"-
"+MethodTrace.Method.Owner.ID;
MethodTrace.Method.Owner.DeveloperGold=
myresults.getString("ownergold");
System.out.println(reqMethod+"-");
System.out.println(MethodTrace.Method.Owner.DeveloperGold);
methodtraceHashMap.put(reqMethod, MethodTrace);
System.out.println("WE ARW IN THE LOOP
"+methodtraceHashMap.get("1-1"));
}
Try this and print the hashmap and see if you still have the overwriting issue
methodtraceHashMap.put(reqMethod+"_"+System.currentTimeMillis(), MethodTrace);
System.out.println("WE ARW IN THE LOOP
"+methodtraceHashMap.get("1-1"));
I think you (or the library you are using) overridden the hashCode of the object you want to store in the HashMap. To fix this issue you should use a Map that isn's searching (and inserting) elements by it's hash code
I recommend you debug your code with following temporary correction:
if (methodtraceHashMap.put(reqMethod, MethodTrace) != null)
throw new RuntimeException("key '" + reqMethod + "' duplication");
As you use String as a hash map key, so you do not have problem with custom hashCode. I am sure, your key is unique and you have to find out what key exactly and then fix it.
I'm working with on a Java program that checks a config file integrity.
On some point, I need to ensure that some mandatory values are setted up, either give it a default value.
So, I made a HashTable<String, String> working like a key => value table. On this table I store all the configuration lines on the file, and then I check it.
The problem comes when a specific value does not exist, for example:
String p = null;
/*...*/
//here I'm trying to get the LOG value
p = this.PAIRS.get("LOG");
if(p.equals(null) || p.equals("")){
//set default value
}
The problem is that I'm getting a NullPointerException, so it would be fine if someone can help me on how to determinate if this.PAIRS.get("LOG"); found a key or not...
Thanks!
EDIT: Solved, the right thing was using == and not an equals.
Thanks again!
If p is null, a NullPointerException will be thrown because it is not an instance of an Object (so the equals method doesn't exist). Checking for null should be done the following way : p == null
p = this.PAIRS.get("LOG");
This code return null if the key is not present and when you are doing below statement it will throw exception
if(p.equals(null) || p.equals("")){
//set default value
}
Instead check null first then do .equals
if(p==null || p.equals("")){
//set default value
}
I've got a MVC based Java application with three models: Room, Student and StudentRoom.
StudentRoom contains an object of Room and Student.
Now I've got the problem that if my SQL query returns no result and I check the value of student's name like this
if(studentRoom.student.name != null) {
}
I'll get a NullPointerException and I don't know how to handle it.
Should I set Student.name = ""; since my query has no result?
if(studentRoom != null && studentRoom.student != null && studentRoom.student.name != null){
//.. Access student
}
Above solution looks a bit weird. you should better use getter/setter methods instead of directly accessing the objects.
Apart from that you can define methods like isStudentAvailable() in studentRoom to check whether it has Student in it or not.
Should I set Student.name = ""; since my query has no result ?
It completely depends on your use case. But I must say better to keep it null as it will raise the exception instead of passing the null check validations.
You might need a try/catch statement for that. Something like this :
try {
// do process here
} catch (NullPointerException npe) {
//to do if student is null
}
But take note, if there are any object that is inside the try statement, a NullPointerException would still be thrown. Hope this helps.
I have this pojo of which there is a list is created below is shown as pojo
public class BrokerInvoiceLineItem {
private Date dealDate;
private String brokerRefId;
private String receiverName;
private double notional;
private double fixedRate;
private Date maturityDate;
private double amount;
}
below is the list which is of above pojo type
List<BrokerInvoiceLineItem> finalBrokerInvoiceLineItemList
now below is the method in which we are fetching the data and storing it to the list finally which we created above
finalBrokerInvoiceLineItemList = brokerInvoice.getLineItems();
now in this list when I inspect while debuging , i get the value of all the attributes at particular index .
now what I am trying to say that lets say at first index the attributes are there mentioned above now lets say if any attribute value lets say if deal date is coming as null at any index then i want to throw exception or lets say brokerRefID is coming as null i want to throw an excpetion so in similiar fashion while iterating over the list at each index i want to check the value of all the 7 attributes that is dealDate, brokerRefId,receiverName,notional,fixedRate,maturityDate,amount , so in the list while iterating if any of the attributes value stored at each index is coming as null i want to throw the exception
so please advise how would I iterate finalBrokerInvoiceLineItemList and check at each index the value of the above total 7 parameters that is whether theere value is null in the finalBrokerInvoiceLineItemList abd if it null then i should throw the exception
what i have tried is shown below is
for(BrokerInvoiceLineItem item : brokerInvoice.getLineItems()) {
if(item.getDealDate() == null)
throw Exception();
}
but the above one is only for one attribute only not all the seven attributes
Then you need to test all the attribute by adding || comperator in the condition as:
for(BrokerInvoiceLineItem item : brokerInvoice.getLineItems()) {
if(item.getDealDate() == null || brokerRefId == null || receiverName == null )// ... etc, add all the attribute you want here.
throw Exception();
}
You have two choices:
Duplicate the if code to check all the other values (either using a logical or || or if you are throwing difference exceptions using different if statements).
Use reflection to scan the class and check all values it contains.
The first option will run faster but has a lot of duplicated code.
The second option will run slower but automatically pick up and check new values added to the class.
I know hashtable doesnt allow null keys ...but how is the below code working.
And what does initializing the Big Decimal to -99 in the below code do.
private static final BigDecimal NO_REGION = new BigDecimal (-99);
public List getAllParameters (BigDecimal region, String key) {
List values = null;
if (region==null) {
region = NO_REGION;
}
Hashtable paramCache = (Hashtable)CacheManager.getInstance().get(ParameterCodeConstants.PARAMETER_CACHE);
if (paramCache.containsKey(region)) {
values = (List) ((Hashtable)paramCache.get(region)).get(key);
}
return values;
}
Am struggling for a long time and dont understand it.
This is an implementation of the null object pattern: a special object, BigDecimal(-99), is designated to play the role of null in a situation where "real" nulls are not allowed.
The only requirement is that the null object must be different from all "regular" objects. This way, the next time the program needs to find entries with no region, all it needs to do is a lookup by the NO_REGION key.
Regions are identified by a BigDecimal in the hashtable (key) - when no region is provided (null) a default value of -99 is used.
It just looks like poor code to me - if something that short makes you "struggle for a long time", that is usually the best indicator.
Just cleaning it up a little and it probably will make a lot more sense:
private static Hashtable paramCache = (Hashtable)CacheManager.getInstance().get(ParameterCodeConstants.PARAMETER_CACHE);
public List getAllParameters (BigDecimal region, String key) {
List values = null;
if (region != null && paramCache.containsKey(region)) {
Hashtable regionMap = (Hashtable) paramCache.get(region);
values = (List) regionMap.get(key);
}
return values;
}
Seems the writer into hashtable used NO_REGION as key for values without a region. So, the reader is doing the same thing.