Nullable (C#) has a bit different meaning, but anyway both Option (Scala) and Nullable can be used to express the notion of "value or nothing".
For example in case when you would like to find substring in a string -- instead of obscure -1 as Int, it would be better to return Option[Int] (in Scala it would be None for nothing).
Is there such class in standard Java? If yes, what it is?
Please note, I am not asking how to write such class.
Update
As I wrote, Nullable has different meaning. Consider this:
Just imagine Map[K,V], and method get which semantics is to get value of key, if there is such key, or nothing when there is no such key.
You cannot use null for two reasons, you cannot use any concrete class for one reason. Option[V] is the way to go.
In Java, the usual way you'd do that would be with null and the Integer, Long, etc. classes (which are the reference type equivalents of the int, long, etc. primitive types; being reference types, the references can be null). If you have a C# background, Integer in Java (with autoboxing) is kind of like int? in C#.
For instance, List#indexOf has this signature:
int indexOf(Object o)
...and does the -1 thing you're talking about. If you were designing List and preferred null, you might have defined it as:
Integer indexOf(Object o)
...and returned null rather than -1 in the "not found" case.
There are these reference type versions of all of the primitive types in Java, and of course, all other types are already reference types so you already have the null option.
You asked more than two years ago, but two months ago, Java SE 8 has introduced java.util.Optional<T>. For an intro, see this Technet article:
Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional!
No. There is no such construct standard in Java.*
There is Option in FunctionalJava or, as yshavit notes, Optional in Guava... Or, you could create your own type... but without proper language support... well, let's just say I avoid Java ;-)
Happy coding.
*I disagree that Integer or Double fulfill this role as they only wrap the fixed set of primitives and are not a generic container. They can be considered to cover the case of Nullable, simply due to Java's fixed set of value types and C#'s limitation of Nullable (only works on ValueTypes), but they do not replace a real Option type.
Do note however, that the Option from FJ or Guava still uses (it must, actually) the wrapper types (e.g. Integer) for handling primitives. Also note that Nullable in C# is not the same as Option in Scala due to the aforementioned restriction.
Related
I'm new to the java language. I'm a php developer. There exist a lot of Variable handling Functions in the php language.
But I find it hard to imagine there aren't any built in functions that check whether value is numeric, is null, etc...
Can anyone explain why this is? Why does java not provide simple functions such as these?
PHP lets you store almost any value in any variable, and converts between types as necessary. Java does not automatically convert between most types - if you want a conversion, you have to do it yourself.
All of the is_something functions would be pointless - you know the type of a variable since you declared it!
If you have a reference to an object, you can determine the type of the object (not the variable) that it refers to using instanceof or reflection:
Object x = "hello";
// the variable x is of type Object, but it refers to a String. How can we tell?
System.out.println(x instanceof Integer); // prints "false"
System.out.println(x instanceof String); // prints "true"
System.out.println(x.getClass().getName()); // prints "java.lang.String"
However, most of the time, this simply isn't something you need to do.
So, all of the is_something functions are unnecessary, and all of the somethingval functions wouldn't fit well in the language (although there's no technical reason they couldn't exist). What else is there?
get_defined_vars - again, redundant. You know what variables are defined because you defined them!
empty (returns true if a variable doesn't exist or contains false). Using a variable that doesn't exist is a compile-time error, so you can just use thing == false (or !thing if it's a boolean) instead of empty(thing).
get_resource_type - the closest match in Java is thing.getClass().getName() instead of get_resource_type(thing).
gettype - useless for the same reason the is_something functions are useless.
import_request_variables - The language Java has no built-in concept of GET variables, POST variables or cookies. Even if it did, this wouldn't work very well, because you'd have to declare all the variables anyway.
is_null - use thing == null instead of is_null(thing).
isset - again, you can't use variables that don't exist. So just use thing != null instead of isset(thing).
serialize and unserialize - Java has a serialization system, which is more complex but more flexible. Look up ObjectOutputStream and ObjectInputStream.
settype - makes no sense, as the type of a variable cannot be changed.
strval - use String.valueOf.
unset - makes no sense. Variables exist until the end of their scope.
print_r and var_dump and var_export - the only ones that might actually be useful and don't already exist. Sadly, it just doesn't exist, though you can get something similar if you override toString in all of your classes.
But i imagine any in build function is not check a value is numeric, is null, etc...
Why java is not provide simple functions such like this?
First reason: Java supports method overloading.
In Java, you typically don't write a single method that handle all sorts of arguments with all sorts of different types. Instead, you can write multiple overloads of the same method: same method name with different declared argument types, and/or different numbers of declared arguments.
The compiler sorts out at compile time which overloaded method to call based on the static types of the argument expressions.
In this model, there is no need to a bunch of functions for sorting out whether values are numeric, null, etcetera.
Second reason: Java does not allow primitive types and object types to be used interchangeably.
For example you cannot declare an argument type that would accept both an int value and a String value. And an int argument type can never accept a null.
(Actually, the primitive wrapper classes like Integer and Java 5's addition of autoboxing / unboxing tend to blur the distinction. But the underlying hard distinction between primitive and reference types remains. Autoboxing is syntactic sugar.)
Third reason: There is instanceof and testing for == null.
As #Malik points out, in the cases where the tests do make sense in Java, they can be implemented with built-in constructs, without resorting to library "functions". The functions are unnecessary.
(AFAIK, no mainstream 3rd-party utility library has implemented the equivalent of the PHP functions you are talking about ... which supports the view that they are unnecessary. If enough people thought the functions were necessary, there would be a library and we would know about it.)
It is also worth noting that most of the "variable handling functions" are to do with dynamically declared variables in PHP. Java doesn't support that. If you want to implement a dynamic binding between names (strings) and values in Java, use a Map class.
PHP as you are aware doesn't tend to care what you store in a variable, you declare a name, give it a value and it will try and interpret it itself. In Java, you explicitly declare the type of variable you would like.
Something like an integer (whole number) can be presented by the primitive data type int, so you could use
int myNumber = 7;
And the code would know for sure that this is an integer, as you have explicitly stated that this is the case. Refer to this page for other java primitives.
If you are using a String (which is an object) in Java, you can use the function isEmpty() to determine if there are any characters in it. You can do a check on objects in Java to see if they have been instantiated by using object == null.
Some compilers will actually give you warnings if you have not initialised variables before you check them, whether these are objects or primitives.
To get a good feel of how data types work in Java, refer to the Oracle documentation I linked, it is very useful, and ill contain a lot of information of other aspects of Java you may have questions with.
First of all why check variable type when you explicitly define a variable with a type. Secondly, you can check the type in Java although you should already know the type.
Integer x = 3;
if (x instanceof Integer) {
System.out.println("Integer");
}
String s = "test";
if (s instanceof String) {
System.out.println("String");
}
As a primitive version of Optional*, Java 1.8 provides OptionalInt, OptionalLong and OptionalDouble.
But I cannot find the equivalent OptionalBoolean class.
Are there any technical reasons against having an OptionalBoolean?
*
An Optional may or may not have the presence of a value, is used as an alternative to null.
This quote explains the considerations behind having primitive streams. I'm assuming the same applied to primitive Optionals. In short, primitive streams (and probably Optionals as well) were created for performance reasons. They didn't create them for all 8 primitive types to reduce code duplication and interface pollution.
Quoting the words of Brian Goetz in the lambda mailing list:
More generally: the philosophy behind having specialized
primitive streams (e.g., IntStream) is fraught with nasty tradeoffs.
On the one hand, it's lots of ugly code duplication, interface
pollution, etc. On the other hand, any kind of arithmetic on boxed ops
sucks, and having no story for reducing over ints would be terrible.
So we're in a tough corner, and we're trying to not make it worse.
Trick #1 for not making it worse is: we're not doing all eight
primitive types. We're doing int, long, and double; all the others
could be simulated by these. Arguably we could get rid of int too, but
we don't think most Java developers are ready for that. Yes, there
will be calls for Character, and the answer is "stick it in an int."
(Each specialization is projected to ~100K to the JRE footprint.)
Trick #2 is: we're using primitive streams to expose things that are best done in the primitive domain (sorting, reduction) but not
trying to duplicate everything you can do in the boxed domain. For
example, there's no IntStream.into(), as Aleksey points out. (If there
were, the next question(s) would be "Where is IntCollection?
IntArrayList? IntConcurrentSkipListMap?) The intention is many streams
may start as reference streams and end up as primitive streams, but
not vice versa. That's OK, and that reduces the number of conversions
needed (e.g., no overload of map for int -> T, no specialization of
Function for int -> T, etc.)
And I should mention that I found that quote in the answer to this question.
boolean values are often abused as parameters. Effective Java 2nd edition warns against abuse of booleans. They often lead to badly readable code if they are not for actual boolean true/false arguments. Instead, Joshua Bloch - the writer - tries to convince people to use double valued enum's:
Prefer two-element enum types to boolean parameters. It makes your code easier to read and to write, especially if you're using an IDE that supports autocompletion. Also it makes it easy to add more options later.
Most OptionalBoolean instances would probably be used incorrectly. This is a good reason for not including one. But I cannot say - only Oracle can - if this is the reason why it is not in there.
Apart for the desire to reduce the magnitude of the combinatorial explosion of primitive type specialisation classes I suspect one major reason for the absence of an OptionalBoolean is that the advantage of such a class is much smaller than the advantage of specialisations for the numeric types.
The reason for why the advantage is smaller is that there are only two different values of the type boolean. Because of this, most of the time you only get two object of type Boolean. Those two are cached as Boolean.TRUE and Boolean.FALSE and reused in most cases, e.g. when booleans are auto-boxed. Numeric wrapper types have a number of cached objects for a small range of values, for other values a new object has to be allocated every time a primitive value is stored in a generic container such as Optional.
So an Optional<Boolean> object is almost as efficient as an OptionalBoolean would be since no new Boolean have to be allocated to put an unboxed boolean into it.
I could also be useful to have two cashed Optional<Boolean> available somewhere in the standard library, as Optional.TRUE/FALSE perhaps. I don't know the reason for why there isn't.
Just to be complete about that: There is indeed an OptionalBoolean in Java 8, but not where you would expect it: it is com.sun.javafx.scene.control.behavior.OptionalBoolean.
But, while JavaFX is nowadays a fixed component of Java, it is not advisable to use it outside of JavaFX stuff.
Apart from that, its interface is completely different from the ones you have in java.util.*.
In the way of learning Java Generics, I got stuck at a point.
It was written "Java Generics works only with Objects and not the primitive types".
e.g
Gen<Integer> gen=new Gen<Integer>(88); // Works Fine ..
But, with the primitive types like int,char etc ...
Gen<int> gen=new Gen<int>(88) ; // Why this results in compile time error
I mean to say, since java generics does have the auto-boxing & unboxing feature, then why this feature cannot be applied when we declare a specific type for our class ?
I mean, why Gen<int> doesn't
automatically get converted to
Gen<Integer> ?
Please help me clearing this doubt.
Thanks.
Autoboxing doesn't say that you can use int instead of Integer. Autoboxing automates the process of boxing and unboxing. E.g. If I need to store some primitive int to a collection, I don't need to create the wrpper object manually. Its been taken care by Java compiler. In the above example you are instantiating an generic object which is of Integer type. This generic object will still work fine with int but declaring int as a generic type is wrong. Generics allow only object references not the primitives.
As you have discovered, you can't mention a primitive type as a type parameter in Java generics. Why is this the case? It is discussed at length in many places, including Java bug 4487555.
The simple explanation: Generics are defined that way.
A good reason from the Java perspective: It simplifies type erasure and translation to byte code for the compiler. All the compiler needs to do is some casting.
With non-primitives the compiler would have to decide whether to cast or to inbox/outbox, it would to need to have additional validating rules (extends and & wouldn't make sense with primitives, should a ? include primitives, yes or no? and so on) and have to handle type conversions (assume you parametize a collection with long and add an int...?)
A good reason from a programmers perspective: operations with a bad performance are kept visible! Allowing primitves as Type Arguments would require hidden autoboxing (inboxing for store, outboxing for read operations. Inboxing may create new objects which is expensive. People would expect fast operations if they parametize a generic class with primitives but the opposite would be true.
That's a very good question.
As you suspected, the abstraction could surely be extended to the type parameters, and made them trasparent to the programmer. In fact, that is what most modern JVM languages do (statically typed ones, of course). Examples include Scala, Ceylon, Kotlin etc.
This is what your example would look like in Scala:
val gen: Gen[Int] = new Gen[Int](80)
Int is just a regular class, just like other classes. There is no primitive-object distinction whatsoever.
As to why Java people did not do it... I don't actually know the reason, but I imagine such an abstraction would not fit with the existing Java specification without overcomplicating the semantics (or without sacrificing the backward compatibility, which is certainly not a viable option).
On the very high level, I know that we need to "wrap" the primitive data types, such as int and char, by using their respective wrapper classes to use them within Java collections.I would like to understand how Java collections work at the low level by asking:"why do we need to wrap primitive data types as objects to be able to use them in collections?"I thank you in advance for your help.
Because Java collections can only store Object References (so you need to box primitives to store them in collections).
Read this short article on Autoboxing for more info.
If you want the nitty gritty details, it pretty much boils down to the following:
Local Primitives are stored on the Stack. Collections store their values via a reference to an Object's memory location in the Heap. To get that reference for a local primitive, you have to box (take the value on the Stack and wrap it for storage on the Heap) the value.
At the virtual machine level, it's because primitive types are represented very differently in memory compared to reference types like java.lang.Object and its derived types. Primitive int in Java for example is just 4 bytes in memory, whereas an Object takes up at minimum 8 bytes by itself, plus another 4 bytes for referencing it. Such design is a simple reflection of the fact that CPUs can treat primitive types much more efficiently.
So one answer to your question "why wrapper types are needed" is because of performance improvement that it enables.
But for programmers, such distinction adds some undesirable cognitive overhead (e.g., can't use int and float in collections.) In fact, it's quite possible to do a language design by hiding that distinction --- many scripting languages do this, and CLR does that. Starting 1.5, Java does that, too. This is achieved by letting the compiler silently insert necessary conversion between primitive representation and Object representation (which is commonly referred to as boxing/unboxing.)
So another answer to your question is, "no, we don't need it", because the compiler does that automatically for you, and to certain extent you can forget what's going on behind the scene.
Read all of the answers, but none of them really explains it simply in layman terms.
A wrapper class wraps(encloses) around a data type (can be any primitive data type such as int, char, byte, long) and makes it an object.
Here are a few reasons why wrapper classes are needed:
Allows null values.
Can be used in collection such as List, Map, etc.
Can be used in methods which accepts arguments of Object type.
Can be created like Objects using new ClassName() like other objects:
Integer wrapperInt = new Integer("10");
Makes available all the functions that Object class has such as clone(), equals(), hashCode(), toString() etc.
Wrapper classes can be created in two ways:
Using constructor:
Integer i = new Integer("1"); //new object is created
Using valueOf() static method:
Integer i = Integer.valueOf("100"); //100 is stored in variable
It is advised to use the second way of creating wrapper classes as it takes less memory as a new object is not created.
To store the Primitive type values in Collection. We require Wrapper classes.
Primitive data types can't be referenced as memory addresses. That's why we need wrappers which serve as placeholders for primitive values. These values then can be mutated and accessed, reorganized, sorted or randomized.
Collection uses Generics as the bases. The Collection Framework is designed to collect, store and manipulate the data of any class. So it uses generic type. By using Generics it is capable of storing the data of ANY CLASS whose name you specify in its declaration.
Now we have various scenario in which want to store the primitive data in the same manner in which the collection works. We have no way to store primitive data using Collection classes like ArrayList, HashSet etc because Collection classes can store objects only. So for storing primitive types in Collection we are provided with wrapper classes.
Edit:
Another benefit of having wrapper classes is that absence of an object can be treated as "no data". In case of primitive, you will always have a value.
Say we have method signature as
public void foo(String aString, int aNumber)
you can't make aNumber as optional in above method signature.
But if you make signature like:
public void foo(String aString, Integer aNumber)
you have now made aNumber as optional since user can pass null as a value.
See Boxing and unboxing: when does it come up?
It's for C#, but the same concept apply to Java. And John Skeet wrote the answer.
Well, the reason is because Java collections doesn't differentiate between primitive and Object. It processes them all as Object and therefore, it will need a wrapper. You can easily build your own collection class that doesn't need wrapper, but at the end, you will have to build one for each type char, int, float, double, etc multiply by the types of the collections (Set, Map, List, + their implementation).
Can you imagine how boring that is?
And the fact is, the performance it brings by using no wrapper is almost negligible for most applications. Yet if you need very high performance, some libraries for primitive collections are also available (e.g. http://www.joda.org/joda-primitives/)
Wrapper classes provide useful methods related to corresponding data types which you can make use of in certain cases.
One simple example. Consider this,
Integer x=new Integer(10);
//to get the byte value of 10
x.byteValue();
//but you can't do this,
int x=10;
x.byteValue(); //Wrong!
can you get the point?
If a variable is known to either hold a specific bit pattern representing null or else information which can be used to locate a Java Virtual Machine object header, and if the method for reading an object header given a reference will inherently trap if given the bit pattern associated with null, then the JVM can access the object identified by the variable on the assumption that there is one. If a variable could hold something which wasn't a valid reference but wasn't the specific null bit pattern, any code which tried to use that variable would have to first check whether it identified an object. That would greatly slow down the JVM.
If Object derived from Anything, and class objects derived from Object, but primitives inherited from a different class derived from Anything, then in a 64-bit implementation it might be practical to say that about 3/4 of the possible bit patterns would represent double values below 2^512, 1/8 of them to represent long values in the range +/- 1,152,921,504,606,846,975, a few billion to represent any possible value of any other primitve, and the 1/256 to identify objects. Many kinds of operations on things of type Anything would be slower than with type Object, but such operations would not be terribly frequent; most code would end up casting Anything to some more specific type before trying to work with it; the actual type stored in the Anything would need to be checked before the cast, but not after the cast was performed. Absent a distinction between a variable holding a reference to a heap type, however, versus one holding "anything", there would be no way to avoid having the overhead extend considerably further than it otherwise would or should.
Much like the String class, Wrappers provide added functionality and enable the programmer to do a bit more with the process of data storage. So in the same way people use the String class like....
String uglyString = "fUbAr";
String myStr = uglyString.toLower();
so too, they can with the Wrapper. Similar idea.
This is in addition to the typing issue of collections/generics mentioned above by Bharat.
because int does not belongs any class .
we convert datatype(int) to object(Interger)
I am trying to create a nullalble object in Java but no idea how to do this , in C# this would be done like this
int? someTestInt;
This allows me to check for for null , while in certain cases i can use a 0 value ,this isnt always possible since certain execution paths allow 0 values
I'm not entirely sure what you want, but if you want to have an integer value that also can be declared null, you probably want to use the Integer class:
Integer nullableInteger = 1;
nullableInteger = null;
System.out.println(nullableInteger); // "null"
There are corresponding classes for each primitive: Character, Long, Double, Byte, etc. The 'standard library' numeric classes all extend the Number class.
Note that Java autoboxes these objects automatically since JDK 1.5, so you can use and declare them just like the primitives (no need for e.g. "new Integer(1)"). So, although they are technically objects (and, therefore, extend the Object class, which the primitive int type does not), you can do basic arithmetics with them. They are converted to object operations at compile time.
Java does not support nullable primitives. You can use the Integer type if you want the ability to store nulls.
(This is a duplicate of this post:
How to present the nullable primitive type int in Java?)
Perhaps try the Integer type in Java.