How to get a array[] out of my LinkedList - java

I need to convert my List:
List<Double> listFoo = new LinkedList<Double>();
to a array of double. So I tried:
double[] foo = listFoo.toArray();
But I get the error:
Type mismatch: cannot convert from Object[] to double[]
How can I avoid this? I could Iterate over the list and create the array step by step, but I don't want to do it this way.

You need to make, generic one
Double[] foo = listFoo.toArray(new Double[listFoo.size()]);
That would be the fastest way.
Using new Double[listFoo.size()] (with array size) you will reuse that object (generally it is used to make generic invocation of method toArray).

You can't make the array of primitives with the standard List class's toArray() methods. The best you can do is to make a Double[] with the generic method toArray( T[] ).
Double[] foo = listFoo.toArray( new Double[ listFoo.size() ] );
One easy way to make a double[] is to use Guava's Doubles class.
double[] foo = Doubles.toArray( listFoo );

It should work if you make foo an array of Doubles instead of doubles (one is a class, the other a primitive type).

Related

Can I create a list of array with Arrays.asList?

Say I want to create a List which contains Integer[] arrays. But
Integer[] foo = {1,2,3};
List<Integer[]> bar = Arrays.asList(foo);
The second line wouldn't compile, because Arrays.asList(foo) will return a List with three Integer elements(namely 1, 2, 3), not a List with a single Integer[] element.
Since the documentation states the parameter of asList method as varargs of type T, I don't understand why the compiler doesn't interpret the second line as single argument of type Integer[] given. How do I get a List of single Array element?
List<Integer[]> bar = new ArrayList<Integer[]>(Arrays.asList(foo));
This is what I actually wanted to do, but it also doesn't compile, for the same reason I believe.
A very similar question was just asked the other day, but I suppose this is different enough for it not to be a duplicate. You need to explicitly specify the generic type for it to compile, like so:
Integer[] foo = {1, 2, 3};
List<Integer[]> list = Arrays.<Integer[]>asList(foo);
Unless you actually need the ability to set the element to a different array, you can use:
List<Integer[]> list = Collections.singletonList(foo);
This is more efficient, because it is specialized to just holding one element: no array has to be created, contains is simply checking equality, size is always 1 etc.
No. Arrays.asList takes a projection of your current array and flattens the first dimension into a List. Since you only have one dimension, all of those elements get collected into the list.
You could do it if you had an Integer[][].
Note: asList accepts a vararg of T (so T...), which is effectively T[]. If you substitute that with Integer[][], you get Integer[], since one dimension of your Integer[][] will satisfy T...'s type requirement.
Varargs in java is just a syntactic sugar in Java. So, there is no difference between.
Arrays.asList(1,2,3) and Arrays.asList(new Integer[]{1,2,3}).
So what you can do like below to solve your problem.
Integer[][] foo = {{1,2,3}};
List<Integer[]> bar = Arrays.asList(foo);
Arrays.asList() generates list of contents of array passed as argument. If you need to create list of arrays, you need to pass to this method array of arrays (e.g. Integer[][]).
When you pass to method Integer[] as argument instead of Integer[][] , it makes a list of contents of that array (in that case these are Integers not arrays of Integers).
Wrapping your array in another array will achieve what you want:
Integer[] foo = {1,2,3};
List<Integer[]> bar = Arrays.asList(new Integer[][]{foo});
// OR
Integer[][] foo = {{1,2,3}};
List<Integer[]> bar = Arrays.asList(foo);
You could also just manually set the first element: (I'd probably say this is more readable, but opinions may vary)
Integer[] foo = {1,2,3};
List<Integer[]> bar = new ArrayList<>();
bar.set(0, foo);

How to create a list of doubles out of an array of doubles

First off, I want to say that I know this has been asked before at the following location (among others), but I have not had any success with the answers there:
Create ArrayList from array
What I am trying to do is the following:
double[] FFTMagnitudeArray = processAudio.processFFT(audioData);
List<Double> FFTMagnitudeList = Arrays.asList(FFTMagnitudeArray);
audioData.setProperty("FFTMagnitudeList", FFTMagnitudeList);
However, I get the error:
"Type mismatch: cannot convert from List<double[]> to List<Double>"
This makes no sense to me, as I thought the List was necessary and the Array.asList(double[]) would return a list of Double, not double[]. I have also tried the following, to no avail:
List<Double> FFTMagnitudeList = new ArrayList<Double>();
FFTMagnitudeList.addAll(Arrays.asList(FFTMagnitudeArray));
List<Double> FFTMagnitudeList = new ArrayList<Double>(Arrays.asList(FFTMagnitudeArray));
And I keep getting the same error.
So how do I create the List?
Change your method to return the object wrapper array type.
Double[] FFTMagnitudeArray = processAudio.processFFT(audioData);
List<Double> FFTMagnitudeList = Arrays.asList(FFTMagnitudeArray);
Or you'll have to manually copy from the primitive to the wrapper type (for the List).
double[] FFTMagnitudeArray = processAudio.processFFT(audioData);
List<Double> FFTMagnitudeList = new ArrayList<>(FFTMagnitudeArray.length);
for (double val : FFTMagnitudeArray) {
FFTMagnitudeList.add(val);
}
The double type is a primitive type and not an object. Arrays.asList expects an array of objects. When you pass the array of double elements to the method, and since arrays are considered as objects, the method would read the argument as an array of the double[] object type.
You can have the array element set the Double wrapper type.
Double[] FFTMagnitudeArray = processAudio.processFFT(audioData);
Using Java 8:
List<Double> FFTMagnitudeList = Arrays.stream(FFTMagnitudeArray).mapToObj(Double::valueOf).collect(Collectors.toCollection(ArrayList::new));
This creates a DoubleStream (a stream of the primitive type double) out of the array, uses a mapping which converts each double to Double (using Double.valueOf()), and then collects the resulting stream of Double into an ArrayList.

Initialize ArrayList with doubles

I'm trying to initialize an ArrayListto use later in my code, but it seems like it doesn't accept doubles.
public ArrayList<double> list = new ArrayList<double>();
It gives an error under 'double', sayin "Syntax error on token "double", Dimensions expected after this token"
An ArrayList doesn't take raw data types (ie, double). Use the wrapper class (ie, Double) instead :
public ArrayList<Double> list = new ArrayList<>();
Also, as of Java 7, no need to specify that it's for the Double class, it will figure it out automatically, so you can just specify <> for the ArrayList.
You need to use the Wrapper class for double which is Double. Try
public ArrayList<Double> list = new ArrayList<Double>();
In Java, ArrayLists (and other generic classes) only accept object references as types, not primitive data types. There are wrapper classes that allow you to emulate using primitives, though: Boolean, Byte, Short, Character, Integer, Long, Float and Double;
public ArrayList<Double> list = new ArrayList<Double>();
//or "public ArrayList<Double> list = new ArrayList<>();" in Java 1.7 and beyond
Values inside are "autoboxed" and "autounboxed" so you can treat doubles as Doubles without problems, and vice versa. You may need to explicitly specify whether you want arguments to be treated as int or Integer when dealing with lists of integral types, though, to disambiguate between cases like remove(int index) and remove(Object o).
public ArrayList<Double> doubleList = new ArrayList<>();
From Java 1.7, you don't need to write Double while initializing ArrayList, so it's your choice to write Double in new ArrayList<>(); or new ArrayList<Double>(); or not.. otherwise it's not compulsory.
Also known as a dynamic array.
No need to pre-determine the number of elements up
front, just add to the array as we need it

List of Arrays in Java

What is the syntax for making a List of arrays in Java?
I have tried the following:
List<int[]> A = new List<int[]>();
and a lot of other things.
I need to be able to reorder the int arrays, but the elements of the int arrays need not to be changed. If this is not possible, why?
Thank you.
Firstly, you can't do new List(); it is an interface.
To make a list of int Arrays, do something like this :
List<int[]> myList = new ArrayList<int[]>();
P.S. As per the comment, package for List is java.util.List and for ArrayList java.util.ArrayList
List<Integer[]> integerList = new ArrayList<Integer[]>();
Use the object instead of the primitive, unless this is before Java 1.5 as it handles the autoboxing automatically.
As far as the sorting goes:
Collections.sort(integerList); //Sort the entire List
and for each array (probably what you want)
for(Integer[] currentArray : integerList)
{
Arrays.sort(currentArray);
}
List is an interface, not a class. You have to choose what kind of list. In most cases an ArrayList is chosen.
List a = new ArrayList();
You've mentioned that you want to store an int array in it, so you can specify the type that a list contains.
List<int[]> a = new ArrayList<int[]>();
While you can have a collection (such as a list) of "int[]", you cannot have a collection of "int". This is because arrays are objects, but an "int" is a primitive.

How to convert an int[] array to a List?

I expected this code to display true:
int[] array = {1, 2};
System.out.println(Arrays.asList(array).contains(1));
The method Arrays.asList(T ...) is, when generics are erased and varargs are transformed, actually equal to a method of type Arrays.ofList(Object[]) (which is the, binary equivalent, JDK 1.4 version of the same Method).
An array of primitives is an Object (see also this question), but not an Object[], so the compiler thinks you are using the varargs version and generates an Object array around your int array. You could illustrate what's happening by adding an extra step:
int[] array = {1, 2};
List<int[]> listOfArrays = Arrays.asList(array);
System.out.println(listOfArrays.contains(1));
This compiles and is equivalent to your code. It also obviously returns false.
The compiler translates varargs calls into calls with a single array, so calling a varargs method that expects parameters T ... with parameters T t1, T t2, T t3 is equivalent to calling it with new T[]{t1, t2, t3} but the special case here is that varargs with primitives will be autoboxed before the array is created if the method needs an object array. So the compiler thinks the int array is passed in as a single Object and creates a single element array of type Object[], which it passes to asList().
So here's the above code once again, the way the compiler implements it internally:
int[] array = {1, 2};
// no generics because of type erasure
List listOfArrays = Arrays.asList(new Object[]{array});
System.out.println(listOfArrays.contains(1));
Here are some good and bad ways to call Arrays.asList() with int values:
// These versions use autoboxing (which is potentially evil),
// but they are simple and readable
// ints are boxed to Integers, then wrapped in an Object[]
List<Integer> good1 = Arrays.asList(1,2,3);
// here we create an Integer[] array, and fill it with boxed ints
List<Integer> good2 = Arrays.asList(new Integer[]{1,2,3});
// These versions don't use autoboxing,
// but they are very verbose and not at all readable:
// this is awful, don't use Integer constructors
List<Integer> ugly1 = Arrays.asList(
new Integer(1),new Integer(2),new Integer(3)
);
// this is slightly better (it uses the cached pool of Integers),
// but it's still much too verbose
List<Integer> ugly2 = Arrays.asList(
Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)
);
// And these versions produce compile errors:
// compile error, type is List<int[]>
List<Integer> bad1 = Arrays.asList(new int[]{1,2,3});
// compile error, type is List<Object>
List<Integer> bad2 = Arrays.asList(new Object[]{1,2,3});
Reference:
Java Tutorial > Classes and Objects > Passing Information to a Method or a Constructor > Varargs
Arrays.asList(T ...)
But to actually solve your problem in a simple way:
There are some library solutions in Apache Commons / Lang (see Bozho's answer) and in Google Guava:
Ints.contains(int[], int) checks whether an array of ints contains a given int
Ints.asList(int ...) creates a List of Integers from an int array
The Arrays.asList(array) will result in a singleton list of an int[].
It works as you expect if you change int[] to Integer[]. Don't know if that helps you though.
Arrays.asList(ArrayUtils.toObjectArray(array))
(ArrayUtils is from commons-lang)
But if you want to just call contains there is no need of that. Simply use Arrays.binarySearch(..) (sort the array first)
This
System.out.println(Arrays.asList(array).contains(array));
returns true.
It seems like your understanding of Arrays.asList(T... a) is wrong. You wouldn't be the first person to make an assumption as to how it works.
Try it with
System.out.println(Arrays.asList(1, 2).contains(1));
Autoboxing just doesn't work the way you want it to in this case. The following code may be a bit verbose, but does the job of converting an int array to a list:
List<Integer> list = new ArrayList<Integer>(array.length);
for (int value : array) {
list.add(value);
}
The following code displays true:
Integer[] array = {1, 2};
System.out.println(Arrays.asList(array).contains(1));
(Your version fails, since Int's not beeing objects, but Int[] is an object. Therefor you will call asList(T... a) with one element beeing a Collection, since it is not possible to have an Collection a.)
When you call
Arrays.asList(array)
on your array of primitives, you get a List instance containing one object: an array of int values! You have to first convert the array of primitives into an array of objects, as #Bozho suggests in his answer.
If you only want to check whether the array contains certain element just iterate over array and search for element. This will take o(n/2). All other solutions are less effective. Any method that copies array to list must iterate over array and therefore this operation only requires n atomic assignments.
I dont think there is a method call you could use. Try it like this
List<Integer> list = new ArrayList<Integer>();
for (int index = 0; index < array.length; index++)
{
list.add(array[index]);
}

Categories

Resources