Having null in a value of a ListResourceBundle implementation - java

In a ListResourceBundle implementation I define an array with some keys containing null values.
It compiles fine the loading process of the bundle containing a null value. However when I call getObject on a key with a non-null value (like in the following example "Pollution" which has value "high"), it gives me a NullPointerException.
Do you have an idea why it happens in that way?
ResourceBundle labels = ResourceBundle.getBundle("bundlething", new Locale("it"));
labels.getObject("Pollution");// here NullPointerException, However Pollution has a \n
value, other keys of the same array do not.
UPDATE:
This is the stacktrace I receive:
Exception in thread "main" java.lang.NullPointerException at
java.util.ListResourceBundle.loadLookup(ListResourceBundle.java:196)
at
java.util.ListResourceBundle.handleGetObject(ListResourceBundle.java:124)
at java.util.ResourceBundle.getObject(ResourceBundle.java:387) at
ResourceBundleThing.main(ResourceBundleThing.java:38)
and this is the bundle I load by passing new Locale("it") as target Locale:
import java.util.ListResourceBundle;
public class bundlething_it extends ListResourceBundle {
private Object [][] contents ={{"Inhabitants",null},{"Pollution",new Double(3.4034)},{"Lollerball",new Integer(132)}};
public Object[][] getContents()
{
return contents;
}
}
There is null corresponding to "Inhabitans" however I am referring only to "Pollution" which has a non-null value. Still I get a NullPointerException; If I remove that null from "Inhabitants" it works.. so it's there the problem, I know. However I would like to know why since I am not using that particular key-value pair.
Does it load all the values as soon as getObject it's called?
Thanks in advance.

The stack trace precisely indicates where the error comes from:
Object[][] contents = getContents();
HashMap<String,Object> temp = new HashMap<>(contents.length);
for (int i = 0; i < contents.length; ++i) {
// key must be non-null String, value must be non-null
String key = (String) contents[i][0];
Object value = contents[i][1];
if (key == null || value == null) {
throw new NullPointerException(); // <-- HERE
}
temp.put(key, value);
}
So, you have your answer: although I haven't seen it mentioned in the documentation, ListResourceBundle doesn't allow null values.

Related

null check is always evaluating to false

import org.json.JSONObject;
String someStringJsonData = "{\"someKey\": " + "null" + "}";
JSONObject someJsonObjectData = new JSONObject(someStringJsonData);
Object someKey = someJsonObjectData.get("someKey");
if (null == someKey) {
System.out.println("someKey is null");
}
I have the above simple snippet of code. I would expect to see "someKey is null" printed, however, my code never goes in the if loop. I tried printing value of someKey and it shows to be null. Not sure what I am missing.
I tried different values of the jsonString from this post but to no avail.
Per its docs, the internal form of the value of a JSONObject can contain values of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object. Therefore, I would not expect its get() method to return null for any key. In your particular case, I would expect someJsonObjectData.get("someKey") to return JSONObject.NULL, which will compare unequal to null.
JSONObject.NULL is a specific object, so it should be safe to perform == comparisons with it:
import org.json.JSONObject;
// ...
void doSomething() {
String someStringJsonData = "{\"someKey\": null}";
JSONObject someJsonObjectData = new JSONObject(someStringJsonData);
Object someValue = someJsonObjectData.get("someKey");
if (someValue == JSONObject.NULL) {
System.out.println("someKey's value is null");
}
}
I needed to do the check for
JSONObject.NULL and not null
https://developer.android.com/reference/org/json/JSONObject.html#NULL.
Printing the class of someKey helped. Thank you everyone for your time!!

Int cannot be dereferenced with getText() [duplicate]

I'm fairly new to Java and I'm using BlueJ. I keep getting this "Int cannot be dereferenced" error when trying to compile and I'm not sure what the problem is. The error is specifically happening in my if statement at the bottom, where it says "equals" is an error and "int cannot be dereferenced." Hope to get some assistance as I have no idea what to do. Thank you in advance!
public class Catalog {
private Item[] list;
private int size;
// Construct an empty catalog with the specified capacity.
public Catalog(int max) {
list = new Item[max];
size = 0;
}
// Insert a new item into the catalog.
// Throw a CatalogFull exception if the catalog is full.
public void insert(Item obj) throws CatalogFull {
if (list.length == size) {
throw new CatalogFull();
}
list[size] = obj;
++size;
}
// Search the catalog for the item whose item number
// is the parameter id. Return the matching object
// if the search succeeds. Throw an ItemNotFound
// exception if the search fails.
public Item find(int id) throws ItemNotFound {
for (int pos = 0; pos < size; ++pos){
if (id.equals(list[pos].getItemNumber())){ //Getting error on "equals"
return list[pos];
}
else {
throw new ItemNotFound();
}
}
}
}
id is of primitive type int and not an Object. You cannot call methods on a primitive as you are doing here :
id.equals
Try replacing this:
if (id.equals(list[pos].getItemNumber())){ //Getting error on "equals"
with
if (id == list[pos].getItemNumber()){ //Getting error on "equals"
Basically, you're trying to use int as if it was an Object, which it isn't (well...it's complicated)
id.equals(list[pos].getItemNumber())
Should be...
id == list[pos].getItemNumber()
Dereferencing is the process of accessing the value referred to by a reference . Since, int is already a value (not a reference), it can not be dereferenced.
so u need to replace your code (.) to(==).
Assuming getItemNumber() returns an int, replace
if (id.equals(list[pos].getItemNumber()))
with
if (id == list[pos].getItemNumber())
Change
id.equals(list[pos].getItemNumber())
to
id == list[pos].getItemNumber()
For more details, you should learn the difference between the primitive types like int, char, and double and reference types.
As your methods an int datatype, you should use "==" instead of equals()
try replacing this
if (id.equals(list[pos].getItemNumber()))
with
if (id.equals==list[pos].getItemNumber())
it will fix the error .
I think you are getting this error in the initialization of the Integer somewhere
try
id == list[pos].getItemNumber()
instead of
id.equals(list[pos].getItemNumber()

Null pointer exception, "Attempt to read from field on a null object reference"

I am making an app in which the user types in a list of tasks, and that list is saved to an array. Each task in the array is an instance of the Assignment class. However, I realized that in java it is not possible to add an element to an array after the array is created. So, what I did was I created an array called tasks which consisted of many null values: Assignment[]tasks = {null, null, null, null, null, null, null, null, null, null, null, null};. When I want to add a task to the array, I just replace the next null value with the object. However, I also need to have an array of just the tasks, with no null values. So I created an array called full_tasks for all of the elements that aren't null:
for (Assignment task: tasks) {
if (task != null) {
realLength += 1;
}
}
Assignment[] full_tasks = new Assignment[realLength];
for (int i=0; i <= full_tasks.length - 1; i++) {
full_tasks[i] = new Assignment(tasks[i].name, tasks[i].days_due, tasks[i].time);
}
So now, the full_tasks array should be an array of all the tasks, none of which are null, right? However, when I run the app, it can't launch the activity, an error it says is caused by a null pointer exception:
Caused by: java.lang.NullPointerException: Attempt to read from field 'java.lang.String com.example.lb.homeworkappv11.Assignment.name' on a null object reference
at com.example.lb.homeworkappv11.Schedule.sortTasks(Schedule.java:64)
The line that the error points to is:
full_tasks[i] = new Assignment(tasks[i].name, tasks[i].days_due, tasks[i].time);
I'm still not totally sure what a null object reference is, but I think it means that one of the elements in the full_tasks array is null. Would that be correct? And if it is, what can I do to make sure that the full_tasks array is only the non-null elements in the tasks array?
Thank you so much!
Edit: the constructor function for the assignment class is:
public Assignment(String name, int days, int time) {
this.name = name;
this.days_due = days;
this.time = time;
this.toSortBy = "nothing";
}
A null reference is just that null. In your code it is tasks[i].name where you try to call name on tasks[i] so tasks[i] is null.
There is one scenario I can think of, where your code would definitely throw a NullPointerException.
So, I will assume your tasks array can look looks like this:
tasks = [task0, null, task2, task3, null, task5]
Then full_tasks will have a size of 4 but
for (int i=0; i <= full_tasks.length - 1; i++) {
full_tasks[i] = new Assignment(tasks[i].name, tasks[i].days_due, tasks[i].time);
}
will throw a NPE as soon as i == 1 because tasks[1] is null.
So, if you want to fill full_tasks with only non-null tasks make sure you got the right indexes of tasks.
Here's what I think
You are just finding the number elements that are not null. You don't know where in the array thest null's are present.
Suppose ONLY the first element is null. So realLength will be 7. The latter for loop runs from i=0 to i=7. When i=0, tasks[i].name tries to access the name field of the first element; but your first element happens to be null`. That's where things go wrong.
Solution:
There are a number of solutions. The most efficient one I can think of uses an ArrayList.
To get around using arrays, you should store the indices of all elements that are not null. That's one way.
Here's another:
for (Assignment task: tasks) {
if (task != null) {
realLength += 1;
}
}
Assignment[] full_tasks = new Assignment[realLength];
int count = 0;
for (Assignment task: tasks) {
if (task != null) {
full_tasks[count] = new Assignment(task.name, tasks.days_due, task.time);
count++;
}
}
You can think of null as something not exists, for example when you try to get task.name, where task is null, you get error, because you try to get name from some something which does not even exists.
Actually what your code is doing now is check how many non-null items in the original array, and try to extract the extra the first n items from the array to a new array.
i.e. if the list is {null, null, non-null, non-null}, it has 2 non-null item, however your code wrongly extracts the list of the first 2 items which are {null, null}
Edit, to actually do what you want:
ArrayList<Assignment> fullTaskList = new ArrayList<Assignment>();
for (Assignment task: tasks) {
if (task != null) {
fullTaskList.add(task);
}
}
//optional
Assignment[] fullTasks = fullTaskList.toArray(new Assignment[fullTaskList.size()]);
The problem in your code is here:
(tasks[i].name, tasks[i].days_due, tasks[i].time).
Although you're counting the real size, there could be some null value in between that is causing it to be get a null object from the list tasks[i].
A good idea to solve this is by using a List instead of an Array. A List can be increased or decreased as you want, you just have to add or remove an item of your object type. For example:
List<Assignment> list = new ArrayList<>();
Assignment assignment1 = new Assignment(etc.);
list.add(assignment1);
list.get(0) //-> returns the Assignment object that you added.
Then you can use list.size() to get the size to know how many items are there, or to remove the last item. And you would have no problems to add new items to the list.
It seems you are trying to copy and compact the tasks array into the full_tasks array (removing the null elements), but you are doing this partially incorrect since you are accessing tasks[i] in the second loop without checking whether its is null.
Instead of:
for (int i=0; i <= full_tasks.length - 1; i++) {
full_tasks[i] = new Assignment(tasks[i].name, tasks[i].days_due, tasks[i].time);
}
you could write something like this:
for (int i = 0, f = 0; i < tasks.length; i++) {
if (tasks[i] != null) {
full_tasks[f] = new Assignment(tasks[i].name, tasks[i].days_due, tasks[i].time);
f++;
}
}
But then again to solve your original problem, regarding the fact that you cannot add any elements to an array, I suggest to use an ArrayList instead of a simple array. This allows you to add items with ArrayList.add(assignment) and remove them again with ArrayList.remove(index).
Seems like "tasks" list is empty. Make sure its get populated or put a null check
like :
if(tasks[i] !=null) {
full_tasks[i] = new Assignment(tasks[i].name, tasks[i].days_due, tasks[i].time);
}

Object as a key in treemap in java 8

CompareObj is a class in java It consists of three attributes String rowKey, Integer hitCount, Long recency
public CompareObj(String string, Integer i) {
this.rowKey = string;
this.hitCount = i%10;
this.recency= (Long) i*1000;
}
Now I created a treeMap
Comparator<CompareObj> comp1 = (e1,e2) -> e1.getHitCount().compareTo(e2.getHitCount());
Comparator<CompareObj> comp2 = (e1,e2) -> e2.getRecency().compareTo(e1.getRecency());
Comparator<CompareObj> result = comp1.thenComparing(comp2);
TreeMap<CompareObj, CompareObj> tM = new TreeMap<CompareObj, CompareObj>(result);
for(int i=0;i<=1000;i++)
{
CompareObj cO = new CompareObj("A"+i, i);
tM.put(cO,cO);
}
for(int i=0;i<=1000;i++)
{
CompareObj cO = new CompareObj("A"+i, i);
CompareObj values = tM.get(cO);
System.out.println(values.getRowKey()); // Line 28: get Null Pointer Exception
}
Also I overide hashCode and Equals. Still I get nullponter exception.
#Override
public int hashCode() {
return Objects.hash(getRowKey());
}
#Override
public boolean equals(Object obj) {
if(this==obj) return true;
if(!(obj instanceof CompareObj)) return false;
CompareObj compareObj = (CompareObj) obj;
return Objects.equals(this.getRowKey(), compareObj.getRowKey());
}
Here when I try to retrive value from treemap back I get Null Pointer exception in the line mentioned. How to solve this
If I want to implement comapareTo() of Comaprable interface, how should I implement if there is multiple sort conditions.
The first thing to understand, is the NullPointerException. If you get that exception on the exact line
System.out.println(values.getRowKey());
then either System.out or values is null. Since we can preclude System.out being null, it’s the values variable, which contains the result of get and can be null if the lookup failed.
Since you are initializing the TreeMap with a custom Comparator, that Comparatordetermines equality. Your Comparator is based on the properties getHitCount() and getRecency() which must match, which implies that when the lookup fails, the map doesn’t contain an object having the same values as reported by these two methods.
You show that you construct objects with the same values but not the code of these getters. There must be an inconsistency. As Misha pointed out, your posted code can’t be the code you have ran when getting the exception, therefore we can’t help you further (unless you post the real code you ran).

Why am I getting a NullPointerException with my array?

I cant figure out why I am getting a NullPointerException. What am I missing here ?
public class CustomJourneyUserInformation {
public IJourneyDetails journeyDetails;
public IUserDetails userDetails;
public ISubscribeJourney subscribedToJourneys;
}
IJourneyDetails, IUserDetails, ISubscribeJourney are all interfaces
In a different activity, I am calling
private CustomJourneyUserInformation[] allJourneyDetails;
allJourneyDetails = new CustomJourneyUserInformation[subscribedToJourneys.length];
if (providerDetails[i] != null)
>>> allJourneyDetails[i].journeyDetails = providerDetails[i];
if (userDetails[i] != null)
allJourneyDetails[i].userDetails = userDetails[i];
if (subscribedToJourneys[i] != null)
allJourneyDetails[i].subscribedToJourneys = subscribedToJourneys[i];
I am getting a null pointer exception in line marked by >>>>
I am sure allJourneyDetails[i] is null here.
It looks like allJourneyDetails[i] is null, since the array is still filled with null after initialization.
Did you expect creating the array to fill the array with non-null values? That's not how it works in Java.
allJourneyDetails = new CustomJourneyUserInformation[subscribedToJourneys.length];
should be
allJourneyDetails = new CustomJourneyUserInformation[providerDetails.length];
too; but #LouisWasserman is right

Categories