Using Integer value in MDC object - java

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.

Related

How to set empty value?

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;

JavaFX: Storing null in a SimpleIntegerProperty

I have a SimpleIntegerProperty which should be able to store null. However, this is not possible, as written in the JavaDoc of IntegerProperty:
Note: setting or binding this property to a null value will set the property to "0.0". See setValue(java.lang.Number).
This also applies to other properties, such as LongProperty, FloatProperty, DoubleProperty, and BooleanProperty (but not to StringProperty, which allows null!). Why is this the case? Is there a workaround to store null in these properties?
The IntegerProperty.setValue(java.lang.Number) method is specified in the interfaces WriteableIntegerValue and WriteableValue. The JavaDoc of WriteableIntegerValue, states:
Note: this method should accept null without throwing an exception, setting "0" instead.
If you are looking at the code of the IntegerPropertyBase class, you can also see that the value is actually stored as a primitive int (which never can be null). This is also specified in the JavaFX API of SimpleIntegerProperty:
This class provides a full implementation of a Property wrapping a int value.
Solution:
You can simply circumvent that by using a SimpleObjectProperty<Integer> instead of a SimpleIntegerProperty, as a SimpleObjectProperty allows null values

How to set individual element of an array to Empty [duplicate]

How do I define a Null string, date or integer in VBA?
I need to be able to assign a Null value to some fields for certain records when data is incomplete or irrelevant, but if I declare a variable as a String, Date or Integer, I get errors when trying to assign a Null value.
Is the only solution to use Variant? If so, then what is the point of all other datatypes in VBA?
Dim x As Variant
x = Null
Only the Variant data type can hold the value Null.
A Variant is a special data type that can contain any kind of data [...] A Variant can also contain the special values Empty, Error, Nothing, and Null.
The "point" of all the other data types is precisely that they cannot contain any ol' kind of data. This has two advantages that I can think of:
It's more difficult for the programmer to assign data of an unintended type to the variable by mistake, since this will be detected at compile time. This can help prevent bugs and make things clearer for you and the next person who will be maintaining your code.
Narrow data types save storage space. Putting integers in a Variant (16 bytes) takes up way more memory than putting them in an Int (2 bytes). This becomes significant if you have large arrays.
Of course, Variants do have their place, as other threads on this site discuss.

Null pointer when moving data around

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).

Return "null" on primitive return type function?

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.

Categories