How can I store an int array into a number array? - java

Integer extends Number so in that sense Number becomes the superclass of int. I want to store an int array into a Number array..
I have the following code.However, it seems it is not allowed in java.
int[] b = {1,2};
Number[] a = b;
Why java does not allow me to store an int array in number array and how do I store this out ?

You can't do that directly, because an "array-of-primitives" is not an "array-of-objects". Autoboxing does not occur with arrays.
But you can use ArrayUtils.toObject(b) (from commons-lang). This will create a new array of the wrapper type (Integer) and fill it with the values from the primitive array:
int[] a = {1,2};
Number[] n = ArrayUtils.toObject(a);

Because int and Integer are two separate types. The first one is a primitive type, and the second one is an object type. Integer extends Number, but int is not even a class, and it thus can't extend anything.

I would guess this has something to do with Number being an abstract class (API Page), meaning the it cannot be used to represent an item, but allows other classes to share functionality. If you could store items in a Number array, they would lose their type, and become instances of Number, which is impossible as it's abstract.

Related

ArrayList storing other than specified datatypes

I have an ArrayList with type Long,but i am trying to insert int value in it.I am expecting int should also be stored in ArrayList as int is smaller in size than long.
int i=1;
ArrayList<Long> obj=new ArrayList<Long>();
obj.add(i);//It is showing error that Storing int is not possible
Whereas the below one is possible
List item
long l=0;
int i=5;
l=i;
Please suggest the reason why ArrayList can't store lower value types.
This:
ArrayList<Long> obj=new ArrayList<Long>();
is declaring that the list will store objects of type Long. It's storing references, and you can't put an Integer in, since an Integer is-not a Long (from the point of view of an object hierachy)
Don't think of the issue in term of numbers. Instead, try this. You have a list of Cats. You can't store a Dog in there. But you could if the list was declared as a list of Animals.
You could declare the list to contain a Number (Longs and Integers are both Numbers), but the fundamental issue is why are you mixing integers and longs in this collection ?
You are doing this:
Long l = 0L;
int i = 5;
l=i;//Type mismatch: cannot convert from int to Long
not this:
long l = 0;
int i = 5;
l = i;
It is not an ArrayList matter, look at this for details.
You just need to cast it to a long to make the above code work:
obj.add((long)i);
Because you specified that the ArrayList contains "Long", it forces all objects that go into it to be Long. And since ArrayList can be used to store any type of data, not just numbers, it doesn't have built-in mechanisms to convert ints to longs for example. Different rules apply.
Java primitives, like int and long, allow automatic conversion to comply with the way that C and C++ work, since Java was based on these languages originally. But it doesn't lead to the cleanest/safest code, and so some other more modern languages have removed even this type of fuziness.
The long variable l also can't store lower value types. The assignment of i to l will implicitly do a Widening Primitive Conversion, and the value is stored as a long.
When you try to insert an int value into a List<Long>, you're implicitly trying to do two conversions:
Widening Primitive Conversion (int to long)
Boxing Conversion (long to Long)
That double conversion will not be applied implicitly, so you have to tell the compiler to do it, by forcing the widening primitive conversion using a cast:
obj.add((long)i);
You have declared obj to be a list of Long and thus it restricts you to use add
/**
* Appends the specified element to the end of this list.
*
* #param e element to be appended to this list
* #return <tt>true</tt> (as specified by {#link Collection#add})
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
Note - where E is from the class definition ArrayList<E> extends AbstractList<E>
to primarily add only the type that your list should be consisting of. Hence changing the code as follows should work :
int i=1;
ArrayList<Long> obj=new ArrayList<Long>();
obj.add(Long.valueOf(i));
Also in your latter part the cast is taken care by the = operator as you assign it in following way :
l=i;
An ArrayList<Long> can only store instances of Long.
You can "apparently" store longs in it, because the long is autoboxed to a Long:
list.add(someLong)
gets compiled to
list.add(Long.valueOf(someLong))
Boxing conversion only applies from primitive to corresponding wrapper type: long to Long, int to Integer etc. It doesn't box an int to a Long, however. The compiler isn't that smart/lenient.
And Java doesn't widen an Integer to a Long, because widening isn't defined for those types: it's only defined for primitive numeric types.
You've just got to make the parameter a long, then it can autobox for you:
obj.add((long) i);
or, without autoboxing:
obj.add(Long.valueOf(i));
Note, in the latter case, int is an acceptable parameter for a method taking a long parameter because of widening conversion. Widening + autoboxing just isn't supported.

How array of primitive types work in Java?

In java, It is said that "every thing instantiated other than primitive type is an object."
I am trying to understand this point using below code (line 4 to be specific).
public class dummy{
public static void main(String[] args){
int[] i = new int[2];
i[0] = new Integer(3); //line 4
i[1] = 3;
System.out.println(int[].class);
System.out.println(i[0]);
}
}
After running
int[] i = new int[4];
Java is creating an object [0,0] of type class [I. The two members within this object [0,0] are primitive data type(but not reference type).
My questions:
Why does Java allow assignment of an object to primitive type member as per below line?
i[0] = new Integer(3); // object of type 'class Integer' getting assigned to i[0]
How do I understand this? In counter, i[0] displays value 3 but not object address.
What is I in class [I? I mean, for class C{}; , C[].class gives class [LC
where [ means "array of" and LC means "instance of 'class C'"
i[0] = new Integer(3);
This involves what's known as auto-unboxing. In the Dark Ages of Java (pre-1.5) we used to have to explicitly box and unbox primitive types. But thankfully the language designers had pity on our poor fingers and added some syntactical sugar. They now let us convert freely between primitives and their wrapper types. Java secretly transforms the above code into this:
i[0] = new Integer(3).intValue();
That's auto-unboxing. Similarly, it will box values for you without your having to ask. If you write:
Integer i = 5;
Java will actually perform:
Integer i = Integer.valueOf(5);
What is I in class [I?
That's I for int.
Java is expecting you to assign an int to an element of the array, but you pass Integer, so it is automatically unboxed as int.
By the way, when you create an Integer[] array, you will also get the same result when doing System.out.println, because Integer.toString just creating the string of it's value, not "object address".
[ means one-dimensional array. I means int.
java/lang/Integer.intValue:()I is being called when you do i[0] = new Integer(3); //line 4 i.e, the compiler is implicitly getting the int value of the Integer and adding it in the array.
For your first question, Java autoboxes primitive types with their wrapper classes (for example, int gets wrapped into the Integer class) and also unboxes wrappers of primitive types.
Here is the documentation: http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
the compiler performs the conversion between primitives and their corresponding objects as a convenience for the programmer.

Is this an object in Java?

When I write this piece of code in Java:
int []Array;
Array = new int[]{1,2,3,4,5};
Is "Array" an object? If so, What type?
From Java Tutorials: Arrays (emphasys mine):
An array is a container object that holds a fixed number of values of a single type.
From this sentence, the answer to your questions:
Is Array an object?
A: Yes.
If so, What type?
A: int[].
In java array is consider as object of the array declared type.
Try this one to get the type of the array.
System.out.println(Array.getClass().getComponentType());
It may be confusing, but you don't create an array with a type called "Array." You define it relative to the type of its contents.
So you create an array of integers like this
int[] first = new int[10];
or
int[] second = new int[] {3, 5, 7, 9};
The brackets tell you it's an array type. And first and second are both objects.
See this resource for more details.
Now just to confuse matters, there is a utility class called Arrays. This class is useful for things like sorting, searching, and other common operations.
If you write the piece of code, as given, then Array is an object of type int[] (as stated in comments).
also an Object (rule of thumb) is "everything" whose type-declarator begins with a majuscle
(uppercase letter)
//short intro to fields:
access modifier | static | final | type | name
public/private/2 more | or not | constant | primitve or Object<T> | lowercase identifier
Examples
private int a;
public static final String greeting = "Welcome!";
thus in general fields and methods are named lowercase.
the only types that do not generate objects are the so called primitives:
int
boolean
char
short
long
double
...
these also have Wrapper-Classes providing additional functionality
Int
Double
Boolean
//and so on;)

Integer vs int types, which is better? [duplicate]

This question already has answers here:
Which one to use, int or Integer
(11 answers)
When to use wrapper class and primitive type
(11 answers)
Closed 9 years ago.
Why does Java have these Integer, Character types and classes
while they are also adapting C's int, char etc
Sometimes when people are creating arrays, they tend to
use Integer[] i = {......}
rather than int[] i = {....};
what is the difference then?
Integer is an object, while int is a primitive. Whenever we pass an int into a function, we pass it as-is.
Integer wraps an int. In its case it is immutable so editing it via reference isn't going to work, but it can be put into generics. This can be set to null while int does not have a possibility of anything beyond 0 or a special value you interpret as a null condition, such as -1 or Integer.MAX_VALUE.
For instance, ArrayList<int> is completely invalid while ArrayList<Integer> must be used with ints being wrapped.
With autoboxing, however, we can immediately add an int to an ArrayList without manually wrapping it, and if we need a primitive when we get() the entry, it'll automatically unwrap it transparently.
In the end if you're doing calculations with a limited number of distinct variables or a fixed array, you should generally use int. When dealing with sets, lists, or maps, you should declare the collection as FooCollection<Integer> then add( an int directly allowing for autoboxing.
Integer, Character and others like this are Objects while int, char and others like this are primitives.
The biggest difference is that an Object can be null while a primitive value can't.
It's recommended to use primitive values where you can because they use less memory.
The only difference we can tell generally is Wrapper is objective representation of primitive.
Wrapper classes are used to represent primitive values when an Object is required.
In java,
Integer is a wrapper class i.e. it is an object while int is a primitive.
Integer default value is null while for int it is 0
There is a concept of autoboxing and auto-unboxing for these two types.
An integer can be converted to an int and vice versa
Followign program demonstrates this
public class TestClass {
int num;
Integer number;
public static void main(String[] args) {
TestClass testClass = new TestClass();
System.out.println(testClass.num);
System.out.println(testClass.number);
testClass.autoBoxInt(testClass.num);
}
public void autoBoxInt(Integer number){
System.out.println(number);
}
}
The output is
0
null
0
The statement System.out.println(testCkass,num) prints int default value i.e. 0. System.out.println(testClass.number) prints Integer default value i.e. null. When you pass testClass.num to a method with parameter Integer, int is automatically converted into and Integer object. so the method prints out 0.
The java collections framework uses autoboxing to convert primitives into Wrapper classes because they cannot take primitive values. They help fast retrieval and storing of objects into collections using hashing and hashcodes. Following example demonstrates this
Set<Integer> numbers = new HashSet<Integer>();
numbers.add(new Integer(10));
numbers.add(new Integer(4));
numbers.add(6);
numbers.add(-9);
numbers.add(new Integer(65));
System.out.println(numbers);
This prints out the set
[4, 65, 6, -9, 10]
To know what hashing is and how hashcodes are used, you can look these links
http://www.thejavageek.com/2013/06/27/what-are-hashcodes/
http://www.thejavageek.com/2013/06/26/what-is-the-significance-of-equals-method-in-java/

Difference between int and Integer

What is the difference between int and Integer. Yes, one is primitive and another one is wrapper, what is the situation to use them correctly.
Also what is the difference between :
int i=0;
++i
and
i++
part 1
One example .. you can use Integer as the key of HashMap but you can't use int. Because an Object is needed.
So where you need an int value as an object there you need to use Integer class.
part 2
++i is pre increment
i++ is post increment
for example
i = 0;
System.out.println(i++) //will print 0 then the i will be 1.
and
i = 0;
System.out.println(++i) // here i wil be incremented first then print 1.
Integer is a wrapper class for int which is a primitive data type. Integer is used when int can't suffice. For example: In generics, the type of the generic class, method or variable cannot accept a primitive data type. In that case Integer comes to rescue.
List<int> list; //Doesn't compiles
List<Integer> list; // Compiles
Moreover Integer comes with a plethora of static methods, like toBinaryString, toHexString, numberOfLeadingZeros, etc. which can come in very handy.
As already explained above
An Integer is an object, whereas an int is a primitive. So you can have a null reference to an Integer and a Set or List of them. You can not do that with an int
I find this null reference very useful, when i have to store int values in database. I can store a null value when I use Integer. But cannot do so when I use int.
An Integer is an object, whereas an int is a primitive. So you can have a null reference to an Integer and a Set or List of them. You can not do that with an int.
A basic explanation is an int is a primitive data type and literally is only a value stored in memory. An Integer is a Java object that wraps an int in a Class with lots of nice/helpful methods that can be called to work with that backing int hidden inside. This is the same with most of the primitive data types, such as boolean and Boolean, char and Character, etc. This is refereed to as Boxing a primitive. Unboxing being the opposite, taking an Object and extracting the backing primative.
Here's an example of how one may use Integer to convert a String into an int (boxed to an Integer)
String someString = "10";
Integer intObj = Integer.parseInt(someString);
System.out.println(intObj.toString());
You'll find that some of the data types have more helpful methods than others. Check the JavaDoc's for each of the types you are interested in, there are a lot of goodies in there!

Categories

Resources