TreeMap that contains String as key and a boolean as value? - java

Hello I tried to create a TreeMap in Java but the compiler gives the error saying "unexpected type".
Can anyone tell me why? Isn't possible to have primitive data types in a Map?
I did solve it by using the java.lang.Boolean instead. But I don't understand why I can't mix a complex data type with a primitive one.

To answer your query,
Maps and other classes which are treated as collections not only serve the purpose of storing data but they also provide methods for comparing. In java comparators are used for the same. In short you need to call methods on the objects you want to compare. If the values are primitive data type, no methods can be invoked on them. This is precisely one of the major reasons why primitive data types are not permitted in collections and related classes.
hope this helps

Isn't possible to have primitive data types in a Map?
No, it isn't. Try <String, Boolean>.

But I don't understand why I can't mix a complex data type with a primitive one.
It's not about mixing complex data types with the primitive types.
The reason is that none of the classes in the Java Collection Framework are designed to support primitive types.
If you need to use any primitive type with the collection framework then you have to use the corresponding wrapper class. e.g. Integer for int ...
Only array supports primitive types.

Isn't possible to have primitive data types in a Map?
No. You cannot use primitive types at all in Java generics.

Related

Why does a key in a Map must be an object and not a primitive and Why cant i use primitive type as key in a map

I have a map: Map abc = new HashMap(). Why is it mandatory for me to use only objects as keys and not primitives?
As for why: The implementations of a Map require Object keys (with an equals() function) to (efficiently) order/store your values for quick retrieval. Primitives do not have an equals() function and are therefore unsuited for the task. (this is basically what #MadProgrammer suggested, except that equals is used in the defintion, and hashCode is just optional for possible implementations).
There is no reason that it would not be possible to programm this, however: in fact you could argue that primitives have the easiest equality and hashCodes to compute! This is probably what is done in TIntArrayList as suggested by Narendra Pathai. And as Jens Schauder states: it would not be worth the hassle, also because autoboxing hides the problem from you most of the time.
In java there is a big divide between primitives and objects/classes.
When you define a method that takes and Object as an argument, you might as well pass a String, or a AbstractSingletonFactoryFacade. But you can't pass a primitive. There is just no way to abstract over multiple primitives. This didn't change with generics.
What one could do is define separate interfaces accepting (and returning) the various primitives. While this would be feasible for thing like List, which have only one type parameter, for Map with two type parameters you would end up with 81 interfaces (8 primitive types + Object squared). Which just isn't worth the hassle.
Of course most of the time this doesn't matter since Autoboxing makes the problem invisible most of the time.

When should I use Boolean instead of boolean? [duplicate]

This question already has answers here:
Boolean vs boolean in Java
(8 answers)
Closed 9 years ago.
When should I use Boolean instead of boolean?. I mean, why would I want to have a null value in a variable which should contain either "true" or "false".. One spontaneous answer (of most people) would be if the value is unknown. i.e, if we don't know whether the value is true or false. But from a programming perspective, I think using Boolean may break the code as we will not know whats inside. So, I think using the primitive type is better than the wrapper.. Correct me if I am wrong.
Generally speaking, the wrapper classes are used in cases where an object is required or strongly preferred. Outside of these situations, it's better to use the primitive types, since they have lower overhead, you can use ==, etc. There are two and a half major situations where this is frequently seen:
Collections. This is now a subset of the next case, but even before Java 5 the Collections classes only supported objects as keys and values, and this hasn't changed.
Generics. Generic types can only work with objects, not primitives, and so if you're using "boolean" as a type parameter, it has to be the wrapper class. For example, if you're using a Future, you have to use a Boolean instead of a boolean. (HT #user949300)
ORM. JPA and other ORM systems technically can use primitive fields, but it's customary to use the wrapper classes, since the overhead is high enough that that doesn't really matter anyway, and the wrapper classes can represent a NULL value that might be present in the database. It's usually still better to forbid nulls and use a primitive for booleans, though, since semantically a default is usually better than "undefined".
Since boolean values are restricted to either true or false, it's uncommon to see them used in Collections or Generics; generally speaking, if you'd have a boolean as a value, you'll just use Collection#contains instead.
IMHO the primitive is better.
Always favor primitives over wrappers. Wherever I am able to use primitives, I go for them because at run time, if we use wrappers, boxing conversions and unboxing conversions happen, and obviously that takes more time. If you use the primitive there, you save that time.
And as usual it depends on your requirements whether you need a Object (which can be null) or you can use a primitive (which cannot be null) in your situation.
For example: Assume you are dealing with collection's then you have no option's,You have to use wrappers :).
Boolean have 3 possible values (null, true, false) while boolean can only be (true, false).
I greatly prefer primitives. However, Booleans are necessary:
When they go into Collections
When you need to allow for a null value. In my experience, this is mainly if they are stored in a database and you need null to indicate that they haven't been read yet, or the user hasn't filled in some form yet.
What if you need to use collections?
Collection will not store primitive types, you need to store object there.
Collections provide so many utility apis, so if you want to use them them a Boolean object is need as collection will need objects.
Although you can always use autoboxing which means you are shielded from object creation and collection takes care of it internally.
Boolean is an object, so you can use it with generics. For example, you can have Map<String,Boolean> to store a true\false value for each string(=key). You can't do Map<String,boolean>, because boolean is not an object - specifically, it's not a subclass of Object. Generics are compile-time wrappers, so Map<Foo,Bar> is actually Map<Object,Object> with smart casting, no matter what Foo and Bar are - as long as they are classes or array types. But they can't be primitives.
The Wrapper classes will be in cases where an object is required or strongly preferred like storing the objects in Collections, cache or session etc, where it requires an object (if not, JRE will convert the primitives to Wrapper classes before they are stored in secondary cache). The below link will explain in better:
Boolean vs boolean in Java
Booolean is an object/reference type that wraps a boolean whereas boolean in a primitive type.
Boolean - You would get more methods which will be useful.
boolean - Will save you lot of memory. But if you use Boolean.valueOf(value) of new Boolean(value), that shouldn't be a cause.
Converting between primitives and objects like this is known as boxing/unboxing.
Click on the below links for more info:
http://javaeye.wordpress.com/2008/06/17/boxing-and-unboxing-conversion/
http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html
http://www.javapractices.com/topic/TopicAction.do?Id=197

Benefits of using wrapper classes over primitives in Java

At a very abstract level I do know that wrapper classes, create an object of the primitive data type but I was curious as to why do we need to use wrapper classes and what benefits do they offer over primitive data types.
Collections in the first place, for example,List<Integer>, you cannot use primitive int here.
Actually any generic class / interface that can work with different object types like
public interface Callable<V> {
V call() throws Exception;
}
Note that wrapping is best done using not new Integer(i) but Integer.valueOf(i) the latter will try to use cache. Unwrapping is done as Integer.intValue(). These wrapping / unwrapping of primitives are so typical operations that Java 5 introduced autoboxing / unboxing
List<Integer> list = new ArrayList<>();
list.add(1);
int i = list.get(0);
this code is automatically converted by Java compiler into
list.add(Integer.valueIf(1));
int i = list.get(0).intValue(); // this is where NullPointerException sometimes happens
Wrapper classes are designed to add more functionality to the primitive types, so that they are compatible with generic code, using the Collection Framework, and many other benefits. However, they are not mean't to replace primitive types.
So, you should use wrappers only when necessary, such as when dealing with generics, because creating an object adds substantial overheads to your program. So, in normal cases, you should stick to primitives.
A wrapper type enables a primitive to hold more contextual meaning. For instance an integer could be anything, whereas a class called Hours, for example, gives the number meaning wherever it is used.
They also enable methods to be written that mutate the said primitive in a consistent and obvious way to consumers. Have a look at Domain Driven Design for more information surrounding this point.
The primitive types just hold value, the wrapper class gives it a name.
With a class name, the compiler can do some static check for you. It makes the interface more meaningful. And you can also defined some method in wrapper classes to validate the primitive values.
Normally, for a small project, i think use primitive types is just fine.
Wrapper objects are normal objects and there references can be null. This allows the usage of a "not set" state which is impossible with primitives.
Integer no = null; // not set
You have to use a magic value like -1 to indicate that a primitive variable is "unset".
Just imagine : your playing a game in that you need to save the status and you want to play in different computer(same game) then u decided to take status (level) to the other computer then you can continue from that state(not from the beginning).. Okay come to the questions if your current weapons status is 3. like { int weapons=1; if(you add weapons by playing some levels okay now its 3) } but you cannot able to store it as object because primitives are different.(lives in stack). so you need weapons as objects (( solution : create Integer Object))
Integer weapon = new Integer(1){ ... }

Do collections convert int to integers sometimes?

I was reading somewhere that even if I use int primitives, adding them to certain types of collections may result in a conversion from int to integers.
When is this the case?
Java collections can only contain objects. Therefore, all collections will Autobox any primitive types you pass them into their equivalent object (boxed) form before storing them. So int primitives will be converted to Integers before being stored in a collection.
Java generics and require their type to be a full-fledged object, which primitives obviously aren't. Note that collections before generics were introduced worked with Objects, so they also required full-fledged objects. Java also introduced auto-boxing and auto-unboxing to make this requirement less of a pain, that means that when you pass an int where a method expects an Integer, an appropriate Integer will automatically be created with the correct value.
It is called auto-boxing and all collections does this since Java 5. It is from int primitive to java.lang.Integer wrapper class (not integers as you mentioned in your post).
The Java guide on autoboxing says about this:
... you can’t put an int (or other primitive value) into a collection. Collections can only hold object references, so you have to box
primitive values into the appropriate wrapper class
Since the JDK's collections maintain data as java.lang.Object references (or Object arrays) internally, they all do have to store the values in boxed/wrapped form.
If you do want to reduce the memory footprint for specialized collections, consider using Trove, which has specialized implementations that store data in primitive arrays.

Determining available operators at runtime

I would like to be able to retrieve the available operators for an object at runtime, possibly in a similar way as the getMethod() call.
In particular, I need to be able to call the less-than/greater-than operators of an object at runtime.
Basically, I have a bunch of primitives that have been cast to the Object object-type. I need to perform comparisons between them at run-time. (I do know that the objects being compared will be of the same original type, and have implemented my own type-checking).
Alternatively.. Maybe there is a way to programatically cast these objects back to their original type, and use their native comparison operators.. somehow?
Thanks for any assistance.
There is no way in Java to get available operators. For comparison the class should (you may do this thru reflection also) implement the Comparable interface.
If they are auto-boxed primitive types, the set of arithmetic operators is identical for all types other than Boolean, and the set of bitwise operators ditto apart from the two FP types.

Categories

Resources