How should I concatenate arrays [duplicate] - java

This question already has answers here:
How can I concatenate two arrays in Java?
(66 answers)
Closed 7 years ago.
I am using a function that returns some integers
int[] return;
This function is inside a loop like this
public static int[] toEOBArray(double[] tempVal)
{
int[] out;
for (int i = 0; i < 10; i++)
{
out = fixArray(tempVal[i]);
}
return out;
}
What I want is as new arrays come from fixArray to add them to the previous results, so in the end I have a big array that will contain all the small arrays resulting from fixArray
What is the most efficient way of doing this?
My main problem is not knowing how to initialize the array that is to hold all the values.

If you want to work only with arrays, you must first find the length of the concatenated array. Then you can use System.arraycopy to copy the small arrays to the output array.
public static int[] toEOBArray(double[] in)
{
int[][] arrays = new int[10][];
int len = 0;
for (int i = 0; i < 10; i++)
{
arrays[i] = fixArray(tempVal[i]);
len += arrays[i].length;
}
int[] out = new int[len];
int offset = 0;
for (int i = 0; i < 10; i++)
{
System.arraycopy(arrays[i],0,out,offset,arrays[i].length);
offset += arrays[i].length;
}
return out;
}

If you insist on working with native arrays (as opposed to a Collection like ArrayList) then you will want to use ArrayUtils class from Apache Common Lang that adds many Collection-like features to Java native arrays, one of which is addAll:
ArrayUtils.addAll(fixArray, tempVal);

Related

Java - Split 2 strings and store it in a single String array [duplicate]

This question already has answers here:
How can I concatenate two arrays in Java?
(66 answers)
Closed 5 years ago.
I have 2 String variables,
String expectedDocsTextReqA = "A1:A2:A3:A4";
String expectedDocsTextReqB = "B1:B2:B3:B4";
And I want to Split these 2 strings and store it in a single String array How to do that?
I'm trying to achieve something like this, But this will throw an exception. Is there any alternate way to do this?
String[] arr = expectedDocsTextReqA.split(":") + expectedDocsTextReqB.split(":");
When you use Split method, this creates an array of strings which cannot be resized. The solution is to convert your array of strings into a list of strings:
String expectedDocsTextReqA = "A1:A2:A3:A4";
String expectedDocsTextReqB = "B1:B2:B3:B4";
List<String> list = new ArrayList<String>();
list.addAll(Arrays.asList(expectedDocsTextReqA.split(":")));
list.addAll(Arrays.asList(expectedDocsTextReqB.split(":")));
for (int i = 0; i < list.size(); i++)
System.out.println(list.get(i));
Probably not the most efficient way to do something like this, but here goes.
String[] split1 = expectedDocsTextReqA.split(":");
String[] split2 = expectedDocsTextReqB.split(":");
//initialize result array size.
String[] result = new String[split1.length + split2.length];
int index = 0;
for (int i = 0; i < split1.length; i++) { //add elements of the first array
result[index] = split1[i]
index++;
}
for (int i = 0; i < split2.length; i++) { //add elements of the second array
result[index] = split2[i]
index++;
}
edit: The List implementation by Joris is probably a more reasonable method of going about this problem.

I do not want to change the array inside the method [duplicate]

This question already has an answer here:
Java Arrays.sort(test) sorts two arrays
(1 answer)
Closed 9 years ago.
when I put an array inside my method public int[] insertionSort(final int array[])
I do not change the array[]
public int[] insertionSort(final int array[]) {
int[] array_for_sorting = array;
final int[]TempArray = array;
int n = array_for_sorting.length;
// printNumbers(TempArray);
for (int j = 1; j < n; j++) {
int key = array_for_sorting[j];
int i = j-1;
while ( (i > -1) && ( array_for_sorting [i] > key ) ) {
array_for_sorting [i+1] = array_for_sorting [i];
i--;
}
array_for_sorting[i+1] = key;
// printNumbers(array_for_sortying);
}
//array = TempArray;
printNumbers(TempArray);// for printing
return array_for_sorting;
}
also, why my TempArray change after the for loop ?
All your array references (array, array_for_sorting, TempArray) are referring the same array object. So, when you modified the array content, it will visible from all its reference.
What does final means here, You can't reassign another array to a final array reference. But, its content can be altered
If you need to copy a arrays, use Arrays.copyOf(array, array.length);
Actually the TempArray and array are two referances to same location in memory, so you are modifying the TempArray when you modify the array
So you need to create a new array like, u can use :
System.arraycopy(array, 0, TempArray, 0, array.length );
Then modify the Array and another array will not change.

Fastest way to convert ArrayList<Integer> into int[] [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to convert List<Integer> to int[] in Java?
In Java, is below the fastest solution:
public convert(ArrayList<Integer> IntegerList) {
int s = IntegerList.size();
int[] intArray = new int[s];
for (int i = 0; i < s; i++) {
intArray[i] = IntegerList.get(i).intValue();
}
}
?
The fastest way is to not use an ArrayList<Integer> in the first place. Try TIntArrayList which wraps an int[], or use a int[] from the start.
If you have to use an ArrayList for some reason and you can't fix it, you are need a way which works and performance is less important.
int[] ints = new int[list.size()];
for(int i=0, len = list.size(); i < len; i++)
ints[i] = list.get(i);
I cant think of any better solution than you have now with plain java.
However if you use Guava, You can probably simplify it.
public convert(List<Integer> list) {
int[] ar = Ints.toArray(list); //Ints is the class from Guava library
}
public void convert(ArrayList<Integer> IntegerList) {
int[] intArray = new int[IntegerList.size()];
int count = 0;
for(int i : IntegerList){
intArray[count++] = i;
}
}
UPDATE : Q. but is a foreach loop any faster/better/different from a regular for loop?
A. here
Integer[] intArray = IntegerList.toArray(new Integer[IntegerList.size()]);

Multidimensional Arrays lengths in Java

How to find the lengths of a multidimensional array with non equal indices?
For example, I have int[][] pathList = new int[6][4]
Without actually hard-coding the indices, I need to find the '6' and the '4'.
I can find the 6 with pathList.length, but how to obtain the '4'?
This will give you the length of the array at index i
pathList[i].length
It's important to note that unlike C or C++, the length of the elements of a two-dimensional array in Java need not be equal. For example, when pathList is instantiated equal to new int[6][], it can hold 6 int [] instances, each of which can be a different length.
So when you create arrays the way you've shown in your question, you may as well do
pathList[0].length
since you know that they all have the same length. In the other cases, you need to define, specific to your application exactly what the length of the second dimension means - it might be the maximum of the lengths all the elements, or perhaps the minimum. In most cases, you'll need to iterate over all elements and read their lengths to make a decision:
for(int i = 0; i < pathList.length; i++)
{
int currLen = pathList[i].length;
}
This is for a 3 dimensional array.
int x[][][]=new int[5][8][10];
System.out.println(x.length+" "+x[1].length+" "+x[0][1].length);
OUTPUT :
5 8 10
Java has "jagged" multidimensional arrays, which means that each "row" in your two-dimensional array can have a different number of components. If you can assume that each row has the same number of components, use:
pathList[0].length;
Otherwise, you will have to iterate:
int maxRowLength = 0;
for (int i = 0; i < pathList.length; i++) {
if (maxRowLength < pathList[i].length) {
maxRowLength = pathList[i].length;
}
}
For 2 D array :-
int x[][] = new int[6][12];
System.out.println(x.length + " " + x[1].length);
OUTPUT : 6 12
pathList.length gives you the number of rows. This means it will output 6 for int[6][4]
pathList[i].length gives you the number of columns in the ith row. Since int[6][4] can be seen as a rectangle it will always output 4.
In java we can define array of arrays which we call multi dimensional arrays.By array of arrays we mean that a single elment of our array is again an array (in java can be of multiple length).To find length of multi array having all subarray of same size,we can use:
int[][]a=new int[3][3];//let a[][] be my array
a.length will work. //a is an object of proxy class and length is its property.
However,if you have subarrays of different sizes then you have to iterate it.
for(i=0;i<a.length;i++)
int cur_size=a[i].length;
In Java we can't use Length field like we used to one-dimensional arrays.
So simply writing a few lines of code solves this problem.
First, you need to know that the output of the Length field in multidimensional arrays is the number of rows.I mean when you have below array
int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};
the result of
System.out.println(numbers.length);
is 2, because you have 2 rows. So, you should use this to solve this problem.
Example:
public class Main {
public static void main(String[] args) {
//Array definition
int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};
//Number of array's elements
int result = 0;
//calculate via loop
for(int i=0; i< numbers.length; i++){
result += numbers[i].length;
}
//output
System.out.println(result);
}
}
You can find '4' by using pathlist[i].length
Please rectify me if I am wrong as I am a novice and would help me in understanding Java better. The following code may help you in understanding.
public class Main {
public static void main(String[] args) {
int num[][] = new int[1][3];
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length; j++) {
num[i][j] = 10;
System.out.println("num [" + i + "] [" + j + "] = " + num[i][j]);
}
}
}
}
3-D array length
int[][][] a = new int[2][3][7];
int length=0;
for(int[][] i:a){
for(int j[]:i){
length+=j.length;
}
}
System.out.println(length);

java: How to split a 2d array into two 2d arrays

I'm writing a program to multiply matrices (2d arrays) as efficiently as possible, and for this i need to split my two arrays into two each and send them off to a second program to be multiplied. The issue I have is how to split a 2d array into two 2d arrays, at specific points (halfway). Does anyone have any ideas?
Lets say you have a 2d array of strings like so
String[][] array= new String[][]
{
{"a","b","c"},
{"d","e","f"},
{"h","i","j"},
{"k","l","m"}
};
Now you need a way to split these arrays at the half way point. Lets get the halfway point. Figure out how big the array is and then cut it in half. Note that you also must handle if the array is not an even length. Example, length of 3. If this is the case, we will use the Math.floor() function.
int arrayLength = array.length;
int halfWayPoint = Math.floor(arrayLength/2);
//we also need to know howmany elements are in the array
int numberOfElementsInArray = array[0].length;
Now we have all the info we need to create two 2d arrays from one. Now we must explicitly copy create and copy the data over.
//the length of the first array will be the half way point which we already have
String [][] newArrayA = new String[halfWayPoint][numberOfElementsInArray];
//this copies the data over
for(int i = 0; i &lt halfWayPoint; i++)
{
newArrayA[i] = array[i];
}
//now create the other array
int newArrayBLength = array.length - halfWayPoint;
String[][] newArrayB = new String[newArrayBLength][numberOfElementsInArray];
/*
* This copies the data over. Notice that the for loop starts a halfWayPoint.
* This is because this is where we left of copying in the first array.
*/
for(int i = halfWayPoint; i &lt array.length; i++)
{
newArrayB[i] = array[i];
}
And your done!
Now if you want to do it a little nicer, you could do it like this
int half = Math.floor(array/2);
int numberOfElementsInArray = array[0].length;
String [][] A = new String[half][numberOfElementsInArray];
String [][] B = new String[array.length - half][numberOfElementsInArray];
for(int i = 0; i &lt array.length; i++)
{
if(i &lt half)
{
A[i] = array[i];
}
else
{
B[i] = array[i];
}
}
And lastly, if you dont want to do it explicitly, you can use the built in functions. System.arraycopy() is one example. Here is a link to its api System.arraycopy()
int half = Math.floor(array/2);
int numberOfElementsInArray = array[0].length;
String [][] A = new String[half][numberOfElementsInArray];
String [][] B = new String[array.length - half][numberOfElementsInArray];
System.arraycopy(array,0,A,0,half);
System.arraycopy(array,half,B,0,array.length - half);

Categories

Resources