How can I convert Vector<double[]> to double[][] in java ?
You can convert a Vector to an array by Vector.toArray():
double[][] array = vector.toArray(new double[0][]);
This maybe slightly faster then for loop, because Vector can utilize System.arraycopy() on its internal array.
This will do it:
double matrix[][] = new double[vector.size()][];
for (int i = 0; i < vector.size(); i++) {
matrix[i] = vector.get(i);
}
Note that this references the same double[] arrays as in your Vector<double[]>. So a change in that will be reflected in the new matrix[][]. If you don't want that then you'll have to create a new double[] for each iteration and copy the values from the old array to the new array.
Muhammed,
WhiteFang is correct... if you're looking for an "out of the box" solution then have a look at Apache's Commons Collections (http://commons.apache.org/collections/)
It's been over a year since I touched Java, but if I recall correctly, "commons" has converters for Vectors... as well as many, many, many other handy bits of kit.
And BTW: If using a Vector is your choice, and you don't have a good reason to NOT use an ArrayList, then use an ArrayList... It's slightly quicker. Except it's NOT threadsafe; whereas all Vectors methods are syncronised. Explanation here: http://skeletoncoder.blogspot.com/2006/09/java-tutorials-arraylist-or-vector.html.
Cheers. Keith.
Related
I am using the following way to put int values from a ResultSet into an int array. This seems very innefficient but I can't figure out how to get an array of primitive int's where I don't know the size beforehand.
List<Integer> ints = ArrayList<Integer>();
while ( results.next ) ints.add( results.getInt( "id" );
int[] intsArray = new int[ ints.size() ];
for ( int i = 0; i < ints.length; i++ ) int[ i ] = ints.get( i ); //auto-boxes here
I need these to be a primitive array as that's what a method requires.
If you don't know the number of values read from the result set you really can't avoid using a list.
But you can avoid using a List<Integer> if you have a list class which can store primitive int values like for example TIntList of the trove project.
In the end you should really measure the performance impact of using intermediate Integer objects before spending too much energy on that question.
Convert ArrayList to array
You would have to guess an initial size and then resize the array as you fill its last element, repeating as needed as you go through your result set.
This behavior is exactly what ArrayList already gives you. But already debugged. ;-)
So just use ArrayList<Integer>. Convert to an array at the end.
You might think to use Collection::toArray. But that utility can only return an array of objects, not primitives.
See this Question, for several good ways to convert to array of primitives.
My choice would be calling on Google Guava. While adding Guava for this one purpose might be overkill, Guava is so useful so often that I add the library by default to most any new Java project.
List< Integer > list = ... ;
int[] values = Ints.toArray( list ) ;
If your deployment environment were extremely tight on memory, or if you had a very large number of elements, or if you were doing this operation so often as to impact performance, only then would I resort to filling-and-resizing an array int manually yourself.
Starting with Java 8 so need a bit of time to get used to it. It's a classical problem, I've an array of objects that I want to transform.
Before Java8 the ideal code would be (no null pointers):
P[] outputArray = new P[inputArray.length];
for (int i =0; i< inputArray.length; i++ )
{
outputArray [i] = inputArray[i].transformToP();
}
What is the best version in Java8 ?
Using the Stream API it's quite simple:
P[] outputArray = Arrays.stream(inputArray).map(e -> e.transformToP()).toArray(P[]::new);
Also method reference can be used (suppose that I is the type of input elements):
P[] outputArray = Arrays.stream(inputArray).map(I::transformToP).toArray(P[]::new);
Note that you may have problems if transformToP() method throws checked exceptions. In this case convert them to unchecked ones or consult this question.
Using a stream over an array is a fine technique as described in Tagir Valeev's answer. However, don't forget about Arrays.setAll. This is a handy shortcut for setting all the elements of an array based on index. To transform an array to a new array by some function, you could do this:
P[] outputArray = new P[inputArray.length];
Arrays.setAll(outputArray, i -> inputArray[i].transform());
You don't have to copy it into a new array. If you want to transform the array in-place, you could do this:
Arrays.setAll(array, i -> array[i].transform());
There is also a parallel variation parallelSetAll.
Under the covers this is just an IntStream.range over the indexes of the input array, but it's sometimes darned convenient for quick one-liners.
I just had an idea to test something out and it worked:
String[][] arr = new String[4][4];
arr[2] = new String[5];
for(int i = 0; i < arr.length; i++)
{
System.out.println(arr[i].length);
}
The output obviously is:
4
4
5
4
So my questions are:
Is this good or bad style of coding?
What could this be good for?
And most of all, is there a way to create such a construct in the declaration itself?
Also... why is it even possible to do?
Is this good or bad style of coding?
Like anything, it depends on the situation. There are situations where jagged arrays (as they are called) are in fact appropriate.
What could this be good for?
Well, for storing data sets with different lengths in one array. For instance, if we had the strings "hello" and "goodbye", we might want to store their character arrays in one structure. These char arrays have different lengths, so we would use a jagged array.
And most of all, is there a way to create such a construct in the declaration itself?
Yes:
char[][] x = {{'h','e','l','l','o'},
{'g','o','o','d','b','y','e'}};
Also... why is it even possible to do?
Because it is allowed by the Java Language Specification, ยง10.6.
This is a fine style of coding, there's nothing wrong with it. I've created jagged arrays myself for different problems in the past.
This is good because you might need to store data in this way. Data stored this way would allow you to saves memory. It would be a natural way to map items more efficiently in certain scenarios.
In a single line, without explicitly populating the array? No. This is the closest thing I can think of.
int[][] test = new int[10][];
test[0] = new int[100];
test[1] = new int[500];
This would allow you to populate the rows with arrays of different lengths. I prefer this approach to populating with values like so:
int[][] test = new int[][]{{1,2,3},{4},{5,6,7}};
Because it is more readable, and practical to type when dealing with large ragged arrays.
Its possible to do for the reasons given in 2. People have valid reasons for needing ragged arrays, so the creators of the language gave us a way to do it.
(1) While nothing is technically/functionally/syntactically wrong with it, I would say it is bad coding style because it breaks the assumption provided by the initialization of the object (String[4][4]). This, ultimately, is up to user preference; if you're the only one reading it, and you know exactly what you're doing, it would be fine. If other people share/use your code, it adds confusion.
(2) The only concept I could think of is if you had multiple arrays to be read in, but didn't know the size of them beforehand. However, it would make more sense to use ArrayList<String> in that case, unless the added overhead was a serious matter.
(3) I'm not sure what you're asking about here. Do you mean, can you somehow specify individual array lengths in that initial declaration? The answer to that is no.
(4) Its possible to extend and shrink primitive array lengths because behind the scenes, you're just allocating and releasing chunks of memory.
I just ported my code from MATLAB to Java, and I need the eigen decomposition of a matrix, specifically I only need the first k values not the full decomposition.
However in JAMA, the eigen-decomposition class computes the full eigen decomposition. I tried to modify it, but it throws some errors. Is there another similar library?
In MATLAB, the function in question is eigs(k,A)
So it's just returning the array of all the eigenvalues. You want to return an array with just the first k values of the array. There are many ways to do this in Java. One is to convert the array to an ArrayList, get a subList of that list, and convert back to an array.
double[] mySubArray = new double[k];
for (int i=0; i < k; i++) {
subArray[i] = myFullArray[i];
}
By the way, this is the library he is referring to: http://math.nist.gov/javanumerics/jama/doc/
In the case you cannot find any existing codes, I guess you should refer to this thesis or maybe this paper.
Maybe you can try another package named EigenDecomposition in http://commons.apache.org/proper/commons-math/javadocs/api-3.6/org/apache/commons/math3/linear/EigenDecomposition.html, there are some methods like getImagEigenvalue(int i), you can get the i-th eigenvalue by this.
I am making an algorithm to save a path of zeroes between 0 1 array
the length of the path will be variable and so i need an array without predefined length
You cannot use array without specifying its length. Consider using ArrayList instead.
You can use an ArrayList which can be between 0 and around 2 billion in lengths.
If you use using a values or 0 and 1, a BitSet may be more efficient.
You can use:
ArrayList<Integer> al = new ArrayList<Integer>();
Note if you wanted to sort this array (for example in ascending order) - you would NOT use
Arrays.Sort(al);
You WOULD use:
Collections.Sort(al);
Use ArrayList instead. An ordinary array cannot be resized so easily - you would have to create a new one of a bigger size and copy the old one into it - I would not recommend this.
ArrayList al = new ArrayList();
al.add(0);
al.add(1);
You can always create array dynamically, e.g. new int[n] where n contains the array length at this moment (not pre-defined at compile time).
But array size cannot be changed. If you need this you should use List instead:
List<Integer> list = new ArrayList<Integer>();
Now you can add and remove elements when you need and the list size will be changed dynamically: you do not have to care about it:
list.add(123);
list.remove(456);
Use ArrayList for a dynamic size.
you can use ArrayList<Boolean> or ArrayList<Integer> and just use the add method. Then utilise the utility methods to get an array out when you are finished constructing the path.
String myArray[] = new Sting[YourVariable];
If speed is a real issue... and you need a dynamically changing array, you could try the following:
// this only works for increasing array-size
int[] tmp = new int[new_bigger_size]; // create a new array
System.arraycopy(array, 0, tmp, 0, array.length); // copy the data
int nextPosition = array.length
array = tmp; // assign the reference
// from position array.length (nextPosition), the new elements can be copied,
// for example:
array[nextPosition] = 120;
....
NOTE! This is very C-ish and not ideal. It is also more difficult to maintain uses more memory during the resizing and is regarded as bad form. Only try this as a last resort and if an ArrayList is really not working for you in terms of speed.
Having said that, does someone have an idea of how much slower (if any) an ArrayList will be?