Do collections convert int to integers sometimes? - java

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.

Related

Relation between Integer Class and int [duplicate]

Autoboxing is the automatic conversion that the Java compiler makes
between the primitive types and their corresponding object wrapper
classes. For example, converting an int to an Integer, a double to a
Double, and so on. If the conversion goes the other way, this is
called unboxing.
So why do we need it and why do we use autoboxing and unboxing in Java?
Some context is required to fully understand the main reason behind this.
Primitives versus classes
Primitive variables in Java contain values (an integer, a double-precision floating point binary number, etc). Because these values may have different lengths, the variables containing them may also have different lengths (consider float versus double).
On the other hand, class variables contain references to instances. References are typically implemented as pointers (or something very similar to pointers) in many languages. These things typically have the same size, regardless of the sizes of the instances they refer to (Object, String, Integer, etc).
This property of class variables makes the references they contain interchangeable (to an extent). This allows us to do what we call substitution: broadly speaking, to use an instance of a particular type as an instance of another, related type (use a String as an Object, for example).
Primitive variables aren't interchangeable in the same way, neither with each other, nor with Object. The most obvious reason for this (but not the only reason) is their size difference. This makes primitive types inconvenient in this respect, but we still need them in the language (for reasons that mainly boil down to performance).
Generics and type erasure
Generic types are types with one or more type parameters (the exact number is called generic arity). For example, the generic type definition List<T> has a type parameter T, which can be Object (producing a concrete type List<Object>), String (List<String>), Integer (List<Integer>) and so on.
Generic types are a lot more complicated than non-generic ones. When they were introduced to Java (after its initial release), in order to avoid making radical changes to the JVM and possibly breaking compatibility with older binaries, the creators of Java decided to implement generic types in the least invasive way: all concrete types of List<T> are, in fact, compiled to (the binary equivalent of) List<Object> (for other types, the bound may be something other than Object, but you get the point). Generic arity and type parameter information are lost in this process, which is why we call it type erasure.
Putting the two together
Now the problem is the combination of the above realities: if List<T> becomes List<Object> in all cases, then T must always be a type that can be directly assigned to Object. Anything else can't be allowed. Since, as we said before, int, float and double aren't interchangeable with Object, there can't be a List<int>, List<float> or List<double> (unless a significantly more complicated implementation of generics existed in the JVM).
But Java offers types like Integer, Float and Double which wrap these primitives in class instances, making them effectively substitutable as Object, thus allowing generic types to indirectly work with the primitives as well (because you can have List<Integer>, List<Float>, List<Double> and so on).
The process of creating an Integer from an int, a Float from a float and so on, is called boxing. The reverse is called unboxing. Because having to box primitives every time you want to use them as Object is inconvenient, there are cases where the language does this automatically - that's called autoboxing.
Auto Boxing is used to convert primitive data types to their wrapper class objects.
Wrapper class provide a wide range of function to be performed on the primitive types. The most common example is :
int a = 56;
Integer i = a; // Auto Boxing
It is needed because of programmers easy to be able to directly write code and JVM will take care of the Boxing and Unboxing.
Auto Boxing also comes in handy when we are working with java.util.Collection types. When we want to create a Collection of primitive types we cannot directly create a Collection of a primitive type , we can create Collection only of Objects. For Example :
ArrayList<int> al = new ArrayList<int>(); // not supported
ArrayList<Integer> al = new ArrayList<Integer>(); // supported
al.add(45); //auto Boxing
Wrapper Classes
Each of Java's 8 primitive type (byte,short,int,float,char,double,boolean,long) hava a seperate Wrapper class Associated with them. These Wrapper class have predefined methods for preforming useful operations on primitive data types.
Use of Wrapper Classes
String s = "45";
int a = Integer.parseInt(s); // sets the value of a to 45.
There are many useful functions that Wrapper classes provide. Check out the java docs here
Unboxing is opposite of Auto Boxing where we convert the wrapper class object back to its primitive type. This is done automatically by JVM so that we can use a the wrapper classes for certain operation and then convert them back to primitive types as primitives result int faster processing. For Example :
Integer s = 45;
int a = s; auto UnBoxing;
In case of Collections which work with objects only auto unboxing is used. Here's how :
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(45);
int a = al.get(0); // returns the object of Integer . Automatically Unboxed .
The primitive (non-object) types have there justification in efficiency.
The primitive types int, boolean, double are immediate data, whereas Objects are references. Hence fields (or variables)
int i;
double x;
Object s;
would need local memory 4+8+8? where for the object only the reference (address) to memory is stored.
Using the Object wrappers Integer, Double and others, one would introduce an indirection, reference to some Integer/Double instance in the heap memory.
Why boxing is needed?
That is a question of relative scope. In a future java it is planned to be able to have an ArrayList<int>, lifting primitive types.
Answer: For now an ArrayList only works for Object, reserving room for an object reference, and managing garbage collection likewise. Hence generic types are Object children.
So if one wanted an ArrayList of floating point values, one needed to wrap a double in a Double object.
Here Java differs from the traditional C++ with its templates: C++ classes vector<string>, vector<int> would create two compilation products. Java design went for having one ArrayList.class, not needing for every parameter type a new compiled product.
So without boxing to Object one would need to compile classes for every occurrence of a parameter type. In concreto: every collection or container class would need a version for Object, int, double, boolean. The version for Object would handle all child classes.
In fact, the need for such diversification already existed in Java SE for IntBuffer, CharBuffer, DoubleBuffer, ... which operate on int, char, double. It was solved in a hacky way by generating these sources from a common one.
Starting with JDK 5, java has added two important functions: autoboxing and autounboxing. AutoBoxing is the process for which a primitive type is automatically encapsulated in the equivalent wrapper whenever such an object is needed. You do not have to explicitly construct an object. Auto-unboxing is the process whereby the value of an encapsulated object is automatically extracted from a type wrapper when its value is required. You do not need to call a method such as intValue() or doubleValue().
The addition of autoboxing and auto-unboxing greatly simplifies writing algorithms, eliminating the bait manually boxing and unboxing of values. It is also helpful to avoid mistakes. It is also very important for generics, who only operate on objects. Lastly, autoboxing facilitates work with the Collections Framework.
Some data structures can accept only objects, no primitive types.
Example: the key in a HashMap.
See this question for more: HashMap and int as key
There are other good reasons, such as a "int" field in a database, which could be NULL as well.
An int in Java cannot be null ; an Integer reference can. Autoboxing and unboxing provide with a facility to avoid writing extraneous code in the conversions back and forth.
why do we have (un)boxing?
to make writing code where we mix primitives and their Object Oriented (OO) alternatives more comfortable/less verbose.
why do we have primitives and their OO alternatives?
primitive types are not classes (unlike in C#), thus they are not subclasses of Object and can not be overridden.
we have primitives like int for performance reasons, and the Object alternatives like Integer for the benefits of OO programming, and as a minor point, to have a good location for utility constants and methods (Integer.MAX_VALUE and Integer.toString(int)).
The OO benefits are visible most easily with Generics (List<Integer>), but are not limited to that, for example:
Number getMeSome(boolean wantInt) {
if (wantInt) {
return Integer.MAX_VALUE;
} else {
return Long.MAX_VALUE;
}
}
ArrayList does not support primitive types only support class. but we need to use primitive types e.g int, double etc.
ArrayList<String> strArrayList = new ArrayList<String>(); // is accepted.
ArrayList<int> intArrayList = new ArrayList<int>(); // not accepted.
The Integer class wraps a value of the primitive type int in an object.so bellow code is accepted.
ArrayList<Integer> intArrayList = new ArrayList<Integer>(); // is accepted.
we can add a value with add(value) method.
To add a String value say "Hello" in strArrayList code is just
strArrayList.add("Hello");
and add a int value say 54 we can write
intArrayList.add(54);
but when we write intArrayList.add(54); compiler convert to the following line
intArrayList.add(Integer.valueOf(54));
As intArrayList.add(54) is easy and more acceptable from user side so compiler does the hard job which is `intArrayList.add(Integer.valueOf(54)); it is autoBoxing.
Similarly to retrieve value we just type
intArrayList.get(0) and compiler convert to <code>intArrayList.get(0).intValue(); which is autoUnboxing.
Because they are different types, and as a convenience. Performance is likely the reason for having primitive types.
Autoboxing: Converting a primitive value into an object of the corresponding wrapper class.
Unboxing: Converting an object of a wrapper type to its corresponding primitive value
// Java program to illustrate the concept
// of Autoboxing and Unboxing
import java.io.*;
class GFG
{
public static void main (String[] args)
{
// creating an Integer Object
// with value 10.
Integer i = new Integer(10);
// unboxing the Object
int i1 = i;
System.out.println("Value of i: " + i);
System.out.println("Value of i1: " + i1);
//Autoboxing of char
Character gfg = 'a';
// Auto-unboxing of Character
char ch = gfg;
System.out.println("Value of ch: " + ch);
System.out.println("Value of gfg: " + gfg);
}
}
Another Special Case is,
Integer intval = null;
int toPrimitive = intval;
System.out.println(toPrimitive);
We are getting NullPointerException for above scenario. that means we can catch NPE

Why do we use autoboxing and unboxing in Java?

Autoboxing is the automatic conversion that the Java compiler makes
between the primitive types and their corresponding object wrapper
classes. For example, converting an int to an Integer, a double to a
Double, and so on. If the conversion goes the other way, this is
called unboxing.
So why do we need it and why do we use autoboxing and unboxing in Java?
Some context is required to fully understand the main reason behind this.
Primitives versus classes
Primitive variables in Java contain values (an integer, a double-precision floating point binary number, etc). Because these values may have different lengths, the variables containing them may also have different lengths (consider float versus double).
On the other hand, class variables contain references to instances. References are typically implemented as pointers (or something very similar to pointers) in many languages. These things typically have the same size, regardless of the sizes of the instances they refer to (Object, String, Integer, etc).
This property of class variables makes the references they contain interchangeable (to an extent). This allows us to do what we call substitution: broadly speaking, to use an instance of a particular type as an instance of another, related type (use a String as an Object, for example).
Primitive variables aren't interchangeable in the same way, neither with each other, nor with Object. The most obvious reason for this (but not the only reason) is their size difference. This makes primitive types inconvenient in this respect, but we still need them in the language (for reasons that mainly boil down to performance).
Generics and type erasure
Generic types are types with one or more type parameters (the exact number is called generic arity). For example, the generic type definition List<T> has a type parameter T, which can be Object (producing a concrete type List<Object>), String (List<String>), Integer (List<Integer>) and so on.
Generic types are a lot more complicated than non-generic ones. When they were introduced to Java (after its initial release), in order to avoid making radical changes to the JVM and possibly breaking compatibility with older binaries, the creators of Java decided to implement generic types in the least invasive way: all concrete types of List<T> are, in fact, compiled to (the binary equivalent of) List<Object> (for other types, the bound may be something other than Object, but you get the point). Generic arity and type parameter information are lost in this process, which is why we call it type erasure.
Putting the two together
Now the problem is the combination of the above realities: if List<T> becomes List<Object> in all cases, then T must always be a type that can be directly assigned to Object. Anything else can't be allowed. Since, as we said before, int, float and double aren't interchangeable with Object, there can't be a List<int>, List<float> or List<double> (unless a significantly more complicated implementation of generics existed in the JVM).
But Java offers types like Integer, Float and Double which wrap these primitives in class instances, making them effectively substitutable as Object, thus allowing generic types to indirectly work with the primitives as well (because you can have List<Integer>, List<Float>, List<Double> and so on).
The process of creating an Integer from an int, a Float from a float and so on, is called boxing. The reverse is called unboxing. Because having to box primitives every time you want to use them as Object is inconvenient, there are cases where the language does this automatically - that's called autoboxing.
Auto Boxing is used to convert primitive data types to their wrapper class objects.
Wrapper class provide a wide range of function to be performed on the primitive types. The most common example is :
int a = 56;
Integer i = a; // Auto Boxing
It is needed because of programmers easy to be able to directly write code and JVM will take care of the Boxing and Unboxing.
Auto Boxing also comes in handy when we are working with java.util.Collection types. When we want to create a Collection of primitive types we cannot directly create a Collection of a primitive type , we can create Collection only of Objects. For Example :
ArrayList<int> al = new ArrayList<int>(); // not supported
ArrayList<Integer> al = new ArrayList<Integer>(); // supported
al.add(45); //auto Boxing
Wrapper Classes
Each of Java's 8 primitive type (byte,short,int,float,char,double,boolean,long) hava a seperate Wrapper class Associated with them. These Wrapper class have predefined methods for preforming useful operations on primitive data types.
Use of Wrapper Classes
String s = "45";
int a = Integer.parseInt(s); // sets the value of a to 45.
There are many useful functions that Wrapper classes provide. Check out the java docs here
Unboxing is opposite of Auto Boxing where we convert the wrapper class object back to its primitive type. This is done automatically by JVM so that we can use a the wrapper classes for certain operation and then convert them back to primitive types as primitives result int faster processing. For Example :
Integer s = 45;
int a = s; auto UnBoxing;
In case of Collections which work with objects only auto unboxing is used. Here's how :
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(45);
int a = al.get(0); // returns the object of Integer . Automatically Unboxed .
The primitive (non-object) types have there justification in efficiency.
The primitive types int, boolean, double are immediate data, whereas Objects are references. Hence fields (or variables)
int i;
double x;
Object s;
would need local memory 4+8+8? where for the object only the reference (address) to memory is stored.
Using the Object wrappers Integer, Double and others, one would introduce an indirection, reference to some Integer/Double instance in the heap memory.
Why boxing is needed?
That is a question of relative scope. In a future java it is planned to be able to have an ArrayList<int>, lifting primitive types.
Answer: For now an ArrayList only works for Object, reserving room for an object reference, and managing garbage collection likewise. Hence generic types are Object children.
So if one wanted an ArrayList of floating point values, one needed to wrap a double in a Double object.
Here Java differs from the traditional C++ with its templates: C++ classes vector<string>, vector<int> would create two compilation products. Java design went for having one ArrayList.class, not needing for every parameter type a new compiled product.
So without boxing to Object one would need to compile classes for every occurrence of a parameter type. In concreto: every collection or container class would need a version for Object, int, double, boolean. The version for Object would handle all child classes.
In fact, the need for such diversification already existed in Java SE for IntBuffer, CharBuffer, DoubleBuffer, ... which operate on int, char, double. It was solved in a hacky way by generating these sources from a common one.
Starting with JDK 5, java has added two important functions: autoboxing and autounboxing. AutoBoxing is the process for which a primitive type is automatically encapsulated in the equivalent wrapper whenever such an object is needed. You do not have to explicitly construct an object. Auto-unboxing is the process whereby the value of an encapsulated object is automatically extracted from a type wrapper when its value is required. You do not need to call a method such as intValue() or doubleValue().
The addition of autoboxing and auto-unboxing greatly simplifies writing algorithms, eliminating the bait manually boxing and unboxing of values. It is also helpful to avoid mistakes. It is also very important for generics, who only operate on objects. Lastly, autoboxing facilitates work with the Collections Framework.
Some data structures can accept only objects, no primitive types.
Example: the key in a HashMap.
See this question for more: HashMap and int as key
There are other good reasons, such as a "int" field in a database, which could be NULL as well.
An int in Java cannot be null ; an Integer reference can. Autoboxing and unboxing provide with a facility to avoid writing extraneous code in the conversions back and forth.
why do we have (un)boxing?
to make writing code where we mix primitives and their Object Oriented (OO) alternatives more comfortable/less verbose.
why do we have primitives and their OO alternatives?
primitive types are not classes (unlike in C#), thus they are not subclasses of Object and can not be overridden.
we have primitives like int for performance reasons, and the Object alternatives like Integer for the benefits of OO programming, and as a minor point, to have a good location for utility constants and methods (Integer.MAX_VALUE and Integer.toString(int)).
The OO benefits are visible most easily with Generics (List<Integer>), but are not limited to that, for example:
Number getMeSome(boolean wantInt) {
if (wantInt) {
return Integer.MAX_VALUE;
} else {
return Long.MAX_VALUE;
}
}
ArrayList does not support primitive types only support class. but we need to use primitive types e.g int, double etc.
ArrayList<String> strArrayList = new ArrayList<String>(); // is accepted.
ArrayList<int> intArrayList = new ArrayList<int>(); // not accepted.
The Integer class wraps a value of the primitive type int in an object.so bellow code is accepted.
ArrayList<Integer> intArrayList = new ArrayList<Integer>(); // is accepted.
we can add a value with add(value) method.
To add a String value say "Hello" in strArrayList code is just
strArrayList.add("Hello");
and add a int value say 54 we can write
intArrayList.add(54);
but when we write intArrayList.add(54); compiler convert to the following line
intArrayList.add(Integer.valueOf(54));
As intArrayList.add(54) is easy and more acceptable from user side so compiler does the hard job which is `intArrayList.add(Integer.valueOf(54)); it is autoBoxing.
Similarly to retrieve value we just type
intArrayList.get(0) and compiler convert to <code>intArrayList.get(0).intValue(); which is autoUnboxing.
Because they are different types, and as a convenience. Performance is likely the reason for having primitive types.
Autoboxing: Converting a primitive value into an object of the corresponding wrapper class.
Unboxing: Converting an object of a wrapper type to its corresponding primitive value
// Java program to illustrate the concept
// of Autoboxing and Unboxing
import java.io.*;
class GFG
{
public static void main (String[] args)
{
// creating an Integer Object
// with value 10.
Integer i = new Integer(10);
// unboxing the Object
int i1 = i;
System.out.println("Value of i: " + i);
System.out.println("Value of i1: " + i1);
//Autoboxing of char
Character gfg = 'a';
// Auto-unboxing of Character
char ch = gfg;
System.out.println("Value of ch: " + ch);
System.out.println("Value of gfg: " + gfg);
}
}
Another Special Case is,
Integer intval = null;
int toPrimitive = intval;
System.out.println(toPrimitive);
We are getting NullPointerException for above scenario. that means we can catch NPE

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.

What is the difference between Integer and int in Java?

For example why can you do:
int n = 9;
But not:
Integer n = 9;
And you can do:
Integer.parseInt("1");
But not:
int.parseInt("1");
int is a primitive type. Variables of type int store the actual binary value for the integer you want to represent. int.parseInt("1") doesn't make sense because int is not a class and therefore doesn't have any methods.
Integer is a class, no different from any other in the Java language. Variables of type Integer store references to Integer objects, just as with any other reference (object) type. Integer.parseInt("1") is a call to the static method parseInt from class Integer (note that this method actually returns an int and not an Integer).
To be more specific, Integer is a class with a single field of type int. This class is used where you need an int to be treated like any other object, such as in generic types or situations where you need nullability.
Note that every primitive type in Java has an equivalent wrapper class:
byte has Byte
short has Short
int has Integer
long has Long
boolean has Boolean
char has Character
float has Float
double has Double
Wrapper classes inherit from Object class, and primitive don't. So it can be used in collections with Object reference or with Generics.
Since java 5 we have autoboxing, and the conversion between primitive and wrapper class is done automatically. Beware, however, as this can introduce subtle bugs and performance problems; being explicit about conversions never hurts.
An Integer is pretty much just a wrapper for the primitive type int. It allows you to use all the functions of the Integer class to make life a bit easier for you.
If you're new to Java, something you should learn to appreciate is the Java documentation. For example, anything you want to know about the Integer Class is documented in detail.
This is straight out of the documentation for the Integer class:
The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.
An int variable holds a 32 bit signed integer value. An Integer (with capital I) holds a reference to an object of (class) type Integer, or to null.
Java automatically casts between the two; from Integer to int whenever the Integer object occurs as an argument to an int operator or is assigned to an int variable, or an int value is assigned to an Integer variable. This casting is called boxing/unboxing.
If an Integer variable referencing null is unboxed, explicitly or implicitly, a NullPointerException is thrown.
(In the above text, the term "variable" means local variable, field or parameter)
Integer refers to wrapper type in Java whereas int is a primitive type. Everything except primitive data types in Java is implemented just as objects that implies Java is a highly qualified pure object-oriented programming language. If you need, all primitives types are also available as wrapper types in Java. You can have some performance benefit with primitive types, and hence wrapper types should be used only when it is necessary.
In your example as below.
Integer n = 9;
the constant 9 is being auto-boxed (auto-boxing and unboxing occurs automatically from java 5 onwards) to Integer and therefore you can use the statement like that and also Integer n = new Integer(9). This is actually achieved through the statement Integer.valueOf(9).intValue();
Integer is an wrapper class/Object and int is primitive type. This difference plays huge role when you want to store int values in a collection, because they accept only objects as values (until jdk1.4). JDK5 onwards because of autoboxing it is whole different story.
This is taken from Java: The Complete Reference, Ninth Edition
Java uses primitive types (also called simple types),
such as int or double, to hold the basic data types supported by the
language. Primitive types, rather than objects, are used for these
quantities for the sake of performance. Using objects for these values
would add an unacceptable overhead to even the simplest of
calculations. Thus, the primitive types are not part of the object
hierarchy, and they do not inherit Object.
Despite the performance
benefit offered by the primitive types, there are times when you will
need an object representation. For example, you can’t pass a primitive
type by reference to a method. Also, many of the standard data
structures implemented by Java operate on objects, which means that
you can’t use these (object specific) data structures to store primitive types. To
handle these (and other) situations, Java provides type wrappers,
which are classes that encapsulate a primitive type within an object.
Wrapper classes relate directly to Java’s autoboxing
feature. The type wrappers are Double, Float, Long, Integer, Short,
Byte, Character, and Boolean. These classes offer a wide array of
methods that allow you to fully integrate the primitive types into
Java’s object hierarchy.
int is a primitive type and not an object. That means that there are no methods associated with it. Integer is an object with methods (such as parseInt).
With newer java there is functionality for auto boxing (and unboxing). That means that the compiler will insert Integer.valueOf(int) or integer.intValue() where needed. That means that it is actually possible to write
Integer n = 9;
which is interpreted as
Integer n = Integer.valueOf(9);
In Java int is a primitive data type while Integer is a Helper class, it is use to convert for one data type to other.
For example:
double doubleValue = 156.5d;
Double doubleObject = new Double(doubleValue);
Byte myByteValue = doubleObject.byteValue ();
String myStringValue = doubleObject.toString();
Primitive data types are store the fastest available memory where the Helper class is complex and store in heap memory.
reference from "David Gassner" Java Essential Training.
int is a primitive type that represent an integer. whereas Integer is an Object that wraps int. The Integer object gives you more functionality, such as converting to hex, string, etc.
You can also use OOP concepts with Integer. For example, you can use Integer for generics (i.e. Collection<Integer>).
int is a primitive data type while Integer is a Reference or Wrapper Type (Class) in Java.
after java 1.5 which introduce the concept of autoboxing and unboxing you can initialize both int or Integer like this.
int a= 9
Integer a = 9 // both valid After Java 1.5.
why Integer.parseInt("1"); but not int.parseInt("1"); ??
Integer is a Class defined in jdk library and parseInt() is a static method belongs to Integer Class
So, Integer.parseInt("1"); is possible in java. but int is primitive type (assume like a keyword) in java. So, you can't call parseInt() with int.
To optimize the Java code runtime, int primitive type(s) has been added including float, bool etc. but they come along with there wrapper classes so that if needed you can convert and use them as standard Java object along with many utility that comes as their member functions (such as Integer.parseInt("1")).

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

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.

Categories

Resources