JavaFX: Storing null in a SimpleIntegerProperty - java

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

Related

Using Integer value in MDC object

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.

How will I use JDK 8 Optional utility class to handle Null Pointer Exception for collections?

JDK 8 adds classes called Optional, OptionalDouble, OptionalInt, and OptionalLong that offer a way to handle situations in which a value may or may not be present. In the past, I would normally use the value null to indicate that no value is present. However, this can lead to null pointer exceptions if an attempt is made to dereference a null reference. As a result, frequent checks for a null value were necessary to avoid generating an exception. These classes provide a better way to handle such situations.
The first and most general of these classes is Optional.
It is important to understand that an Optional instance can either contain a value of type T(bounded type) or be empty. In other words, an Optional object does not necessarily contain a value.
Optional(value-based class) does not define any constructors, but it does define
several methods that let you work with Optional objects. For example, I can
determine if a value is present, obtain the value if it is present, obtain a
default value when no value is present, and construct an Optional value.
I tried something like this,
Optional<String> noVal = Optional.empty();
Optional<String> hasVal = Optional.of("ABCDEFGH");;
if(noVal.isPresent())
System.out.println("This won't be displayed");
else
System.out.println("noVal has no value");
if(hasVal.isPresent())
System.out.println(hasVal.get());
String defStr = noVal.orElse("Default String");
System.out.println(defStr);
But, i am unable to make out how to use it with collections so as to handle null? Can someone.
Your question lacks information about what you are actually going to do. Without a description of an operation, e.g. showing the code performing the action without using Optional, we can’t tell you how to do the same using Optional or whether this is possible at all.
One way of dealing with references which might be null is to construct an Optional via Optional.ofNullable(…). This can also be used within an action that is applied to Collection elements:
List<String> list=Arrays.asList("hello", null, "world", null);
list.forEach(x->Optional.ofNullable(x).ifPresent(System.out::println));
However, most operations on collections which you want to formulate using new Java 8 features are good candidates for the stream API. While forEach is suitable for a simple action, even the short detour via Optional makes it complex enough to benefit from the Stream API:
list.stream().filter(Objects::nonNull).forEach(System.out::println);
does the same without nested operations.
So Optional is a good return type for a single element which might be absent, e.g. like for Stream.findAny, but when processing collections, there are usually better alternatives.

TObjectIntMap (Trove 3) How can 'int get(java.lang.Object key)' method return null? Is it a documentation mistake?

I have been looking into the documentation of Trove4j library. Particularly the TObjectIntMap interface. According to the documentation of the library the get method returns null if the key is not present in the map. The documentation I am referring to can be seen here:
http://trove4j.sourceforge.net/javadocs/gnu/trove/map/TObjectIntMap.html#get%28java.lang.Object%29
At the time of reading (27/02/2014) the documentation states
int get(java.lang.Object key)
"Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key."
My question is:
How is it possible for the method to return null when the return type is the primitive int. As far as I know it is only possible for Integer references to be null. Is it a documentation error?
You are right, int can't be null. Thus their documentation is inconsistent.
To give you a bit of insight how Trove is built: they have templates for all primitive and object permutations of datastructures, so it is understandable that you can't keep everything consistent. You should report this to the project however so they can fix that.
To check if there is a value for a key, you should use the method
public boolean containsKey(java.lang.Object key)
or (a more hacky solution) is to check for the default value for no entries:
gnu.trove.impl.Constants.DEFAULT_INT_NO_ENTRY_VALUE
which defaults to 0, if you didn't override the gnu.trove.no_entry.int property.

Why doesn't Mockito RETURNS_DEFAULT return a default String?

In the following example (mockito 1.10.19):
MyClass myClass = Mockito.mock(MyClass .class, RETURNS_DEFAULTS);
String s = myClass.getName();
Why does this result in s == null rather than an empty String?
It indeed promised null for a String in ReturnsEmptyValues. But it seems so obvious to return "" that I'm wondering if there is a reason for it not to.
EDIT: updated version to 1.10.19 from 1.8, because no documentation is available anymore for 1.8.
From the link you posted;
Default answer of every Mockito mock.
Returns appropriate primitive for primitive-returning methods
Returns consistent values for primitive wrapper classes (e.g. int-returning method retuns 0 and Integer-returning method returns 0,
too)
Returns empty collection for collection-returning methods (works for most commonly used collection types)
Returns description of mock for toString() method
Returns null for everything else
From the FAQ:
What values do mocks return by default?
In order to be transparent and unobtrusive all Mockito mocks by
default return 'nice' values. For example: zeros, falseys, empty
collections or nulls.
It was probably done to stay consistent with any other methods which return null for any other non-collection, non-primitive Wrapper objects.
You can always implement your own Answer to pass to mock which returns empty strings for String returning methods.
It wasn't thought of at design time and now for stability reason, this behavior didn't change.
There's an non exposed answer called ReturnsMoreEmptyValues that returns as the type name suggests more empty values.
You could also take a look at the Mockito.RETURNS_SMART_NULLS answer that use ReturnsMoreEmptyValues internally and features more interesting debug informations.
Note this links to 1.10.19 version javadoc, however this behavior remains unchanged in version 2.x at the time of this writing.
Because the designer of Mockito decide to use that as a default
Because null is also the default value of fields in a Java object
According to the Mockito code for all non collections and non simple types it returns null. String is an subtype of Object and it's "empty" value is null, not "".IMHO It is a design decision if you represent empty value for string as null or "".
YourService service = mock(YourService.class, RETURNS_MOCKS);
when(service.callYourFunc()).thenReturn(mockValue);
ReflectionTestUtils.setField(serrviceParent, "service", service);
serrviceParent is service that you are testing and it contains field YourService that couldn't return mockValue that you want

Need a strategy to lookup property for dynamically generated dropdown component

I need to set the null value string for a dropDownChoice component. The default value for null choice is "Choose One", which is hardcoded in the Wicket AbstractSingleChoice class.
The usual way of overriding this is to define a property resource.
However my DropdownChoice component is dynamically generated at runtime, and added to a panel (which is within a datatable). The DropDownChoice is not specifically referenced in the markup.
I'm looking for suggestions on how to programmatically override the default null value string in this situation. It would be nice if the DropDownChoice constructor had an additional parameter for this.
Do I need to programmatically create a new property resource?
Hope this makes sense.
You can override AbstractSingleSelectChoice.getNullKey() and AbstractSingleSelectChoice.getNullValidKey() in order to make Wicket retrieve a localized resource from a .properties or .xml file that does not have the component id as part of the key. This is documented in this JIRA issue: Open DropDownChoice null value internationalization key
For instance:
DropDownChoice ddc = new DropDownChoice(id, model, choices){
#Override
protected String getNullKey(){ return "customDdcNullValue"; }
#Override
protected String getNullValidKey(){ return "customDdcNullValue"; }
}
Will retrieve the <option>'s text from the customDdcNullValue property.
These methods seem to have been added in version 1.4.4, if you're on 1.3, you could always use an IChoiceRenderer with the DropDownChoice that returns the proper String in the case of null value. Note that you could retrieve it from resources (with getString(), or StringResourceModel), or grab the value from database/cache if necessary. This may depend on how are you already localizing the choices for non-null values.
Also, you could use the source code of AbstractSingleSelectChoice.getDefaultChoice() to roll your own DropDownChoice with this behavior.
UPDATE: Another way of handling this is to provide your own custom value that represents null, or no-choice. Just remember to use setNullValid(false) on the DropDownChoice to prevent null from appearing when there is a selected value, and initialize the ddc's model with your no-selection value when you still don't know its value in order to avoid Wicket provide null in the getDefaultChoice() call.
When defining the value for your no-selection option, pay special attention to this part of AbstractSingleSelectChoice.getDefaultChoice():
// Null is not valid. Is it selected anyway?
if ((selected == null) || getNoSelectionValue().equals(selected) ||
selected.equals(EMPTY_STRING))
{
Take into account that getNoSelectionValue() returns -1, so please do not use -1, or an empty string, as your custom null value. I learnt this the hard way, believe me, it's not pleasing.
You should use localisation feature to achieve it. There is a method org.apache.wicket.resource.loader.IStringResourceLoader.loadStringResource(org.apache.wicket.Component,java.lang.String) which returns a string value to display for a given component. The string will be a resource key, for your case it is the "nullValid" string, IIRC.
So, you can implement your custom resource manager which will pick data from a database instead of .properties files.

Categories