Converting Array of Primitives to Array of Containers in Java
Apache Commons
Apache Commons / Lang has a class ArrayUtils that defines these methods.
- All methods called
toObject(...)
convert from primitive array to wrapper array - All called
toPrimitive(...)
convert
from wrapper object array to
primitive array
Example:
final int[] original = new int[] { 1, 2, 3 };
final Integer[] wrappers = ArrayUtils.toObject(original);
final int[] primitivesAgain = ArrayUtils.toPrimitive(wrappers);
assert Arrays.equals(original, primitivesAgain);
Guava
But then I'd say that Arrays of wrapped primitives are not very useful, so you might want to have a look at Guava instead, which provides Lists of all numeric types, backed by primitive arrays:
List<Integer> intList = Ints.asList(1,2,3,4,5);
List<Long> longList = Longs.asList(1L,2L,3L,4L,5L);
// etc.
The nice think about these array-backed collections is that
- they are live views (i.e. updates to the array change the list and vice-versa)
- the wrapper objects are only created when needed (e.g. when iterating the List)
See: Guava Explained / Primitives
Java 8
On the other hand, with Java 8 lambdas / streams, you can make these conversions pretty simple without using external libraries:
int[] primitiveInts = {1, 2, 3};
Integer[] wrappedInts = Arrays.stream(primitiveInts)
.boxed()
.toArray(Integer[]::new);
int[] unwrappedInts = Arrays.stream(wrappedInts)
.mapToInt(Integer::intValue)
.toArray();
assertArrayEquals(primitiveInts, unwrappedInts);
double[] primitiveDoubles = {1.1d, 2.2d, 3.3d};
Double[] wrappedDoubles = Arrays.stream(primitiveDoubles)
.boxed()
.toArray(Double[]::new);
double[] unwrappedDoubles = Arrays.stream(wrappedDoubles)
.mapToDouble(Double::doubleValue)
.toArray();
assertArrayEquals(primitiveDoubles, unwrappedDoubles, 0.0001d);
Note that the Java 8 version works for int
, long
and double
, but not for byte
, as Arrays.stream() only has overloads for int[]
, long[]
, double[]
or a generic object T[]
.
Converting an array of objects to an array of their primitive types
Unfortunately, there's nothing in the Java platform that does this. Btw, you also need to explicitly handle null
elements in the Integer[]
array (what int
are you going to use for those?).
Cast primitive type array into object array in java
Primitive type cannot be transformed in this way.
In your case, there is an array of double values, cause of 3.14.
This will work:
List<Object> objectList = new ArrayList<Object>();
objectList.addAll(Arrays.asList(0,1,2,3.14,4));
Even this works :
List<Object> objectList = new ArrayList<Object>();
objectList.addAll(Arrays.asList(0,"sfsd",2,3.14,new Regexp("Test")));
for(Object object:objectList)
{
System.out.println(object);
}
UPDATE
Ok, there as there was said, there is not direct way to cast a primitive array to an Object[].
If you want a method that transforms any array in String, I can suggest this way
public class CastArray {
public static void main(String[] args) {
CastArray test = new CastArray();
test.TestObj(new int[]{1, 2, 4});
test.TestObj(new char[]{'c', 'a', 'a'});
test.TestObj(new String[]{"fdsa", "fdafds"});
}
public void TestObj(Object obj) {
if (!(obj instanceof Object[])) {
if (obj instanceof int[]) {
for (int i : (int[]) obj) {
System.out.print(i + " ");
}
System.out.println("");
}
if (obj instanceof char[]) {
for (char c : (char[]) obj) {
System.out.print(c + " ");
}
System.out.println("");
}
//and so on, for every primitive type.
} else {
System.out.println(Arrays.asList((Object[]) obj));
}
}
}
Yes, it's annoying to write a loop for every primitive type, but there is no other way, IMHO.
Java Streams toArray with primitives
Why can I use 'toArray(float[][]::new)' but not
'toArray(float[]::new)' ?
As you said, Arrays.stream(wrappers).map(f -> f.FloatValue)
is a Stream<Float>
so toArray(float[]::new)
does not work as you are required to provide an IntFunction<Float[]>
, not an IntFunction<float[]>
.
On the other hand, Arrays.stream(wrappers).map(f -> convert1DprimitiveArray(f))
is a Stream<float[]>
so toArray(IntFunction<A[]>)
requires an IntFunction<float[][]>
which is what float[][]::new
is for.
.toArray(float[]::new)
would work if you had a Stream<float>
, which is not possible since you can't have a primitive type as a generic parameter.
How to convert an ArrayList containing Integers to primitive int array?
You can convert, but I don't think there's anything built in to do it automatically:
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = integers.get(i).intValue();
}
return ret;
}
(Note that this will throw a NullPointerException if either integers
or any element within it is null
.)
EDIT: As per comments, you may want to use the list iterator to avoid nasty costs with lists such as LinkedList
:
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
Iterator<Integer> iterator = integers.iterator();
for (int i = 0; i < ret.length; i++)
{
ret[i] = iterator.next().intValue();
}
return ret;
}
What is the best way of converting ListLong object to long[] array in java?
Since Java 8, you can do the following:
long[] result = values.stream().mapToLong(l -> l).toArray();
What's happening here?
- We convert the
List<Long>
into aStream<Long>
. - We call
mapToLong
on it to get aLongStream
- The argument to
mapToLong
is aToLongFunction
, which has along
as the result type. - Because Java automatically unboxes a
Long
to along
, writingl -> l
as the lambda expression works. TheLong
is converted to along
there. We could also be more explicit and useLong::longValue
instead.
- The argument to
- We call
toArray
, which returns along[]
java function that work with objects and primitives
Sadly generics won't work here as generics do not cover primitives but they do cover primitive arrays. Primitive arrays are also not autoboxed into a wrapper class array. That is something you would have to do manually, but that is very very slow. One solution is to provide an override for each primitive, similar to how Arrays.sort is implemented. This creates a lot of duplicate code. Another solution is to use an Array interface similar to ArrayList that emulates an Array, get/set methods for indices, and provide subclasses for each primitive and one for objects. You can then use the Array interface and not care what the actual type is.
Java - array types to Object type cast
How does java convert array types to Object types ?
Array types are already a sub-class of Object, so there's no need for any conversion.
how does java convert a primitive type array to an instance of Object ? Also while copying to 'dest', how does it know how to copy it without knowing the type ?
A primitive type array is already an instance of Object, so no conversion is required. The JVM knows at runtime the types of elements stored in the source and target arrays. If they don't match, ArrayStoreException
is thrown.
how does a[1][3] change if i changed b[1][3] and what is the correct way to make a copy of a ?
System.arraycopy
doesn't do deep copy. It copies the primitive or reference in each position of the source array to the target array. When an element of the source array is itself a reference to a sub-array, the reference is copied to the target array as is. Therefore a[1] == b[1]
(they refer to the same array object), so changing b[1][3]
changes a[1][3]
.
If you want each sub-array to be a copy of the original sub-array, you have to execute System.arraycopy
for each sub-array separately after executing System.arraycopy
for the main array.
Related Topics
Java.Lang.Outofmemoryerror: Java Heap Space in Maven
Convert a String of Hex into Ascii in Java
How to Make Anonymous Inner Classes in Java Static
How to Avoid Type Safety Warnings with Hibernate Hql Results
Exception in Thread "Main" Java.Util.Nosuchelementexception
How to Monitor Java Memory Usage
Java Floating Point High Precision Library
How to Use Mockito When We Cannot Pass a Mock Object to an Instance of a Class
Differencebetween Jdk Dynamic Proxy and Cglib
Java String - See If a String Contains Only Numbers and Not Letters
Java Reflection: How to Get the All Getter Methods of a Java Class and Invoke Them
Java 'File.Delete()' Is Not Deleting Specified File