Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert Long[] to long[] (primitive) java

Tags:

How do i convert Long[] to long[]? For example i know how to convert if it is not array as below.

long ll = (Long)Object[1].longValue() 

But how do i convert for an array, the below is not right but can anyone correct it?

long[] l_ar = (Long[])Object[]   
like image 927
user1595858 Avatar asked Aug 19 '12 19:08

user1595858


People also ask

How do you convert primitive int to primitive long in java?

Java int can be converted to long in two simple ways: This is known as implicit type casting or type promotion, the compiler automatically converts smaller data types to larger data types. Using valueOf() method of the Long wrapper class in java which converts int to long.

Can we assign long to long in java?

In Java Long is an object and like any object it can be null. long is a primitive type and cannot be null.


2 Answers

You could steal a solution based on ArrayUtils

Long[] longObjects = { 1L, 2L, 3L }; long[] longArray = ArrayUtils.toPrimitive(longObjects); 
like image 147
Reimeus Avatar answered Sep 29 '22 11:09

Reimeus


There are no standard API method for doing that (how would null-elements be handled?) so you would need to create such a method yourself.

Something like this (will throw NullPointerException on any object beeing null):

public static long[] toPrimitives(Long... objects) {      long[] primitives = new long[objects.length];     for (int i = 0; i < objects.length; i++)          primitives[i] = objects[i];      return primitives; } 
like image 34
dacwe Avatar answered Sep 29 '22 12:09

dacwe