My problem is that I don't know how to set empty value. Because first 3 values must be empty.
I tried to set NaN or just didn't print value then it does not pass the test.
So, how I set empty value? It is possible or I just don't understand my assignment?
It's an assignment for Weighted Moving Average.
It's must look like this but as I said I don't know how to print empty value.
Thanks for the help.
What you call empty depends on your problem. In Java, empty values are usually reflected as null. The problem is that you cannot use nulls with primitive types such as double. You probably want to use a wrapper type, java.lang.Double in your case.
For example :
Double emptyValue = null;
Related
I was using MDC for logging in my spring boot application. Along with that I was also maintaining a graph. I was fetching the values from MDC to draw the graph. It requires Integer values not the string values. I don't want to make use of String values and then type caste it explicitly after fetching the values for the graph reason being the code may break during type casting as it may contain null values (even though there would be no such scenario as I have kept the default value as "0" but still I want to avoid this).
If I try
MDC.put("Speed", "0");
It works fine.
But it shows error for
MDC.put("Speed", 0);
Please tell how can I put an integer value in the MDC object.
MDC only supports string values as keys and values. What you can do instead, to avoid type casting errors for null values, is to use Integer class instead of the primitive int.
I'm querying a database and some of the results I'm getting are null. I'm setting these values to a variable with a datatype of double. Let's call the variable "results". So I tried setting up an if statement to see it equals Null which of course didn't work. Here is the code I have for that if statement:
if (results == null)
{
results = 0;
}
The error I get with this code is:
The operator == is undefined for the argument type(s) double, null
Is there a better way to determine if it's null?
Firstly, a Java double cannot be a Java null, and cannot be compared with null. (The double type is a primitive (non-reference) type and primitive types cannot be null.) I'm therefore assuming the following:
The "null" you are trying to detect is a NULL stored in the database that you are querying.
You are using JDBC to query the database.
If you call ResultSet.getDouble(...), that returns a double not a Double, the documented behavior is that a NULL (from the database) will be returned as zero. (See javadoc linked above.) That is no help if zero is a legitimate value for that column.
Changing the declared type of result to Double instead of double as suggested by Toby's answer will not help. When the database contains NULL, the value assigned to result will be a Double(0.0), not a null.
Here are two options that will work:
Use ResultSet.wasNull() to test for a (database) NULL ... immediately after the getDouble(...) call.
Use ResultSet.getObject(...), and test for null using ==.
The getObject method will deliver a (non-NULL) value as a Double (assuming that the column type is double). It is documented to return null for a NULL. (For more information, this page documents the default mappings of SQL types to Java types, and therefore what actual type you should expect getObject to deliver.)
I would recommend using a Double not a double as your type then you check against null.
A double primitive in Java can never be null. It will be initialized to 0.0 if no value has been given for it (except when declaring a local double variable and not assigning a value, but this will produce a compile-time error).
More info on default primitive values here.
To say that something "is null" means that it is a reference to the null value. Primitives (int, double, float, etc) are by definition not reference types, so they cannot have null values. You will need to find out what your database wrapper will do in this case.
How are you getting the value of "results"? Are you getting it via ResultSet.getDouble()? In that case, you can check ResultSet.wasNull().
I believe Double.NaN might be able to cover this. That is the only 'null' value double contains.
I've got a function filling a HashMap(rMap) of String arrays. Once certain conditions are met e.g r.Map.size() != 0 I then, in another file (rMap is a Global variable) call the following String array[] = rMap.get(0) from this I attempt to System.out.println(array[0]) .
Thats the run of the program and I get a null pointer at System.out.println(array[0]);. Anyone have any ideas why this happens?
EDIT: I'm filling the map like so..
String center[] = new String[] { tname, tmessage, tlink, tsname };
Global.rMap.put(index, center);
Where all values in the array are variables that are strings. So the value I'm accessing it tname and It's not equal to null. I've checked. My Key value is a String
The array reference is null, most likely because no value (or a null) has been added to rMap, with key 0.
If possible, use generics to ensure that your keys are the correct type. You might also print out the values of the map prior to fetching array to see what is in the map. Stepping through the code with a debugger, with a watch on the rMap will also show what the map contains and when it is changed.
How are you filling the map? Are you certain that you're putting an non-null entry with an Integer key of 0 into it?
Well, we can be pretty certain that you aren't. Possible reasons:
An error in the filling code that results in the intended put not being executed, or with a different key value
You're using Short or Byte objects as keys
You're putting a null value into the map under the 0 key
You can answer this question for yourself by running the code in a debugger and looking at the contents of the map.
Update:
My Key value is a String
Well, that's your problem right there. rMap.get(0) will look for an Integer, and it will not match the entry for a String "0".
HashMap allows null values, so the value you are getting with String array[] =rMap.get(0); may be null. Accessing the null array then throws the NPE.
Try rMap.get(Integer.valueOf(0));
It's an issue when you invoke the get method of Map implementation, the signature of get method of java.util.Map is get(java.lang.Object),thus,any object will be accepted as its argument.
The key that works fine is either pass a string(value=0) as a key or overrides the hashCode and equals methods of argument object that is not a java.lang.String object.
The get() method of Hashmap takes a key, not an index, to identify the value you want to get. If you want an ordered list of items, you'll need to use a List subclass (or enforce the ordering, yaourself). If you want to use a Hashmap, use the keys() method to get an enumeration of all the map's keys.
(removed above text, due to question clarification. leaving below text as, even though it's not the problem, it is an important consideration)
Also, you'll need to be very careful not to create race conditions, since you're working across threads. While Java's native Hashtable is synchronized, that doesn't mean the data in it is. That is, you can MyObj obj = get(xxx) in one htread, Nd start manipulating the obj in two separate threads, possibly stepping on each other. Depending upon your application, you may want to use Hashtable.remove() so that the data is gone from the map and cannot be re-used, or you may need some synchronized blocks (remove() may well be the simpler implementation, thoguh you'd have to gracefully handle conditions where the map first has data, then that data is gone).
I have a function which returns an int value for a given key (from a HashMap<String, Integer>). If the key doesn't exist, I want to return something the caller can check for. It seems that, most commonly, this would be a "returns -1 if key doesn't exist" kind of thing. However, I can't reserve -1 for that purpose in my case, because negative numbers are feasible values for keys which do exist.
The only other options I have been able to come up with are the following:
Change return type to Integer wrapper class and check for null
Return something very unlikely, such as Integer.MIN_VALUE
Make an additional boolean keyExists(String key) function which should always be called first
Switch to float and use NaN instead
I am writing this in Java, but people from similar language backgrounds are welcome to post. Thanks!
The first option is, in my opinion, the cleanest. Magic numbers like -1 and Integer.MIN_VALUE are kind of messy, especially when the values aren't intuitive. That is an idiomatic C solution, which Java developers will hate you for. Depending on what you're actually using this for you could also throw a "KeyNotFoundException" if this only happens in "exceptional" circumstances.
I vote for throwing a checked exception here. Generally I dislike checked exceptions but it seems like a reasonable thing to do in this case. The case where the value is not present will need to be handled separately from the case where the value is present, using an exception would make that clear.
Actually your idea to add a keyExists method is the best of the ideas you list, because it doesn't rely on the user knowing to look for a special value. If you go that way then you could throw an exception as a backup plan in case the map contents change between the call to keyExists and the retrieval.
Although it depends heavily on the application and know constraints, I would prefer #1 above. The reason is because then it is explicit - it is always better to have an explicit situation than an implicit - such as MIN_VALUE - in my experience.
Another option is to have a wrapper object that contains the result value as a primitive int, but also has a status value or something similar. So it could be something like:
public class Wrapper {
private int value = Integer.MIN_VALUE;
private boolean isValid;
// appropriate getters and setters etc.
}
You could also include an enum instead of a boolean to have a state instead, depending on the complexity of the problem. If you see this element holding composite information - sets of information keyed of single keys, or something similar - a container object or status object can be very valuable in those cases.
float is unsafe as not all int values can be accurate represented as int values. long is a better options as all int values can be safely stored as long and you will have plenty more values for not-found.
If you are using a Map you have an Integer object anyway so why not return that (or null)
If you really want to use primitives (for efficiency ??) I suggest you look at TObjectIntHashMap instead. This uses primitive int values. To check for absense, you have to check containsKey() seperately.
Two situations are typical:
You have a high expectation of
finding a value for a particular
key.
You are not sure if a particular key
has a value stored.
If assumption 1 is wrong, then it's likely to indicate a bug, so protect your assumption in the access method with an assertion.
If 2 applies, how would you be sure about what's returned? so provide a test method such as "keyExists" and know absolutely before accessing the map.
In case 1, no checking is required, which is much cleaner, but the access will fail if you are wrong.
With special cases such as -1 or Integer.MIN_VALUE it is very hard to be sure that they won't be used.
Languages like Haskell, Scala and C# have special types to convey presence / absence of a value which is far better than use of null (if you forget to test you will likely get a NullPointerException)
Option 5: Throw an Exception
Although, in this case, I'd vote for using the Integer class.
I think you should combine options #1 and #3, since that's consistent with the behavior of the underlying HashMap. From HashMap's get method documentation:
Returns the value to which the specified key is mapped in this identity hash map, or null if the map contains no mapping for this key. A return value of null does not necessarily indicate that the map contains no mapping for the key; it is also possible that the map explicitly maps the key to null. The containsKey method may be used to distinguish these two cases.
Change return type to Integer wrapper class and check for null.
This is the more common option.
I've got a problem with java's instanceof. Here's a gap of code that causes me trouble:
LinkedList<Double> currentSummary = summary.getFirst().getQuantiles();
...more code...
while (!currentSummary.isEmpty()){
if (currentSummary.getFirst() instanceof Double){
orderedSummary.add(new ComparableWrapper<Double, Float>(currentSummary.removeFirst(), currentEpsilon));
}
}
So, my problem is, that the if-condition won't become true. Those elements in currentSummary are either null or an Double-value. And I'm trying to reject elements that are null. At first I just added them and ran into NullPointerException later on, because of some (but not all!) elements being null.
An example element of currentSummary is e.g. [null, 0.09861866469135272, 10.137051035535745, 107.12083740100329, 371.4371264801424, 827.432799544501, 1206.251577083686].
Anybody got's an idea why instanceof won't work in that case? I tried it with currentSummary.getFirst() instanceof Object as well...
Thanks in advance!
I assume you want to remove the first entry at each iteration, in order to traverse the complete list. However, you remove the entry only when the instanceof condition is true. Therefore, it seems like the loop becomes infinite when it encounters the first null value (unless you dropped parts of the code, and we don't see the complete loop body)
Is it possible that due to auto-boxing/unboxing, the Double objects get unboxed to the primitive double, and therefore they are not instance of Double class.
If that is the case, would it be better if you check for non-null elements instead?
Why don't you just use a simple null check?
if (currentSummary.getFirst() != null){ ... }
It is possible, by using raw types (LinkedList instead of LinkedList<Double>), to add non-Double entries to your LinkedList<Double>. Those elements would fail the instanceof Double test. But those entries would pass an instanceof Object test.