Number of columns in 2d array declaration - java

I want to read a text file and insert it into a 2d array. Here is my code.
List<String> list2 = new ArrayList<String>();
String thisLine = null;
while ((thisLine = input1.readLine()) != null) {
list2.add(thisLine);
}
double[][] X;
X = new double[list2.size()][];
String[] temp;
String delims = ",";
for (int k1 = 0; k1 <= (X.length - 1); k1++) {
String line = input.readLine();
temp = line.split(delims);
for (int i = 0; i < temp.length; i++) {
X[k1][i] = Double.parseDouble(temp[i]);
}
}
The problem is that it returns nothing and as soon as I specify the number of columns in 2d array declaration line, everything is fine. Based on my java knowledge, the number of columns in 2d array declaration is not necessary and in my project (Since we apply different datasets), the number of columns is not specified.

A 2d array is basically an array of arrays. Let's call it an outer array consisting of inner arrays.
When initializing a 2d array, it's true that you only have to declare the length of the outer array. I.e. the number of rows. By doing this, only the outer array will be initialized. The inner arrays are yet to be initialized.
In fact, these two arrays will contain the exact same elements:
double[][] array1 = new double[3][];
double[][] array2 = {null, null, null};
To initialize an inner array, you could do one of these:
array1[0] = new double[4];
array1[0] = new double[] {1.0, 3.14, 42.0, 2.718};
In your case, you could simply put this in your code to initialize the inner arrays:
temp = line.split(delims);
X[k1] = new double[temp.length]; //<- Add this line

X = new double[list2.size()][];
You have now created a jagged array, which is an array of arrays, bound by list2.size().
X[k1][i] = Double.parseDouble(temp[i]);
You have attempted to dereference a spot in the jagged array which does not exist. This is bad.
If the number of columns in your spec isn't specified, then it's provided either by the length of the arguments you parse, or implicitly by the element(s) you attempt to place into that location.
This would work, since it defines an array, which is what the jagged array needs...
X[k1][i] = new double[] {Double.parseDouble(temp[i])};
...but it would only give you a two-dimensional array effective as new Double[list2.size()][1].
Considering that you make use of String[] temp, perhaps instead, you want to use that as the condition on your jagged array? Here's a quick and dirty way to do it that involves more variables than I'd like, but would work:
String[] temp;
double[] tempDouble;
for (int k1 = 0; k1 <= (X.length - 1); k1++) {
temp = input.readline().split(delims);
tempDouble = new double[temp.length];
for(int i = 0; i < temp.length; i++) {
tempDouble[i] = Double.parseDouble(temp[i]);
}
// a bit further down, you can use the array as part of your jagged array.
X[k1] = tempDouble;
}

Related

Passing 2D Array argument with JACOB

I have a COM method I'm trying to invoke, where there's an argument of type 'object' which must be a 2D double safe array, a collection of lat/long points. How can I create a SafeArray in JACOB to send through the COM interface?
I've tried just passing a 2D array as an object in the object list. The method doesn't return error, but I do not see the results I expect in FalconView (rendering of the polygon).
double polyPoints[][] = new double[5][2];
polyPoints[0][0] = 75.3;
polyPoints[0][1] = 4.5;
polyPoints[1][0] = 3.8;
polyPoints[1][1] = 4.8;
polyPoints[2][0] = 2.3;
polyPoints[2][1] = 2.5;
polyPoints[3][0] = 5.3;
polyPoints[3][1] = 6.5;
polyPoints[4][0] = 0.3;
polyPoints[4][1] = -1.5;
// Can't recreate Variant or SafeArray from double[x][y] array;
Object[] polygonArgs = new Object[] {m_mainLayerHandle, polyPoints, 1};
Variant returnAddPolygon = Dispatch.invoke(mainLayerDispatch, "AddPolygon", Dispatch.Method, polygonArgs, new int[1]);
System.out.println("Polygon Handle: " + returnAddPolygon.getInt());
Object[] refreshArgs = new Object[] {m_mainLayerHandle};
Variant refreshVariant = Dispatch.invoke(mainLayerDispatch, "Refresh", Dispatch.Method, refreshArgs, new int[1]);
The second arument documentation:
lat_lon_array
a two dimensional SAFEARRAY of doubles. The first dimension contains the latitude values. The second dimension contains the longitude values
It seems that SafeArray supports 1 Dimensional, 2 Dimensional, and N-Dimensional arrays using some somewhat unclear constructors. Given the 2D double array I created above, I was able to copy the data in to a 2D Double Safe Array. It would certainly be more efficient to create the double[][] up front, but I'm doing this in some prototype code. There may be ways to copy entire arrays in to the safe array... I am not sure.
// 2D array of type double. First dimension size 5, second dimemnsion size 2.
SafeArray safeArray = new SafeArray(Variant.VariantDouble, 5, 2);
for(int i = 0; i < 5; i++) {
for (int j = 0; j < 2; j++) {
// set the value of safearray[i][j] to value polyPoints[i][j]
safeArray.setDouble(i, j, polyPoints[i][j]);
}
}

Java array with empty second brackets

In Java you can do this
int[][] i = new int[10][];
Does this just create 10 empty arrays of int? Does it have other implications?
It creates a 10-entry array of int[]. Each of those 10 array references will initially be null. You'd then need to create them (and because Java doesn't have true multidimensional arrays, each of those 10 int[] entries can be of any length).
So for instance:
int i[][] = new int [10][];
i[0] = new int[42];
i[1] = new int[17];
// ...and so on
Executing your code creates an array of size 10, each element of which can hold a reference to a int[], but which are all initialized to null.
In order to use the int[]s, you would have to create new int[] for each of the element, something like this:
for (int n = 0; n < 10; n++)
i[n] = new int[10]; // make them as large as you need
Yes, it does; however, each of those arrays are null. You have to then initialize each of those sub-arrays, by saying int[10][0] = new int[MY_SIZE], or something similar. You can have arrays with different lengths inside the main array; for example, this code would work:
int[][] i = new int[10][];
for(int ind = 0; ind<10;ind++){
i[ind]=new int[ind];
}
It is just an array of arrays.
Here you create ten new int[0] arrays. You have to manually initialize it, it's useful when you don't need square matrix:
int[][] array = new int[10][];
for (int i = 0; i < array.length; i++) {
array[i] = new int[i];
}
If you need square matrix you can do:
int[][] array = new int[10][10];
And it will be initialized with default values.
That is just the declaration, you need to initialize it. The 10 arrays would be null initially.

double row length of 2D array

I'm trying to double the length of a 2D array as I add values to it. I know for a 1D an array the code for this is:
int oneD[] = new int[10];
//fill array here
oneD = Arrays.copyOf(oneD, 2 * oneD.length);
so if I have a 2D array and only want to double the amount of rows while keeping say 2 columns I figured I would just do this:
int twoD[][] = new int[10][2];
//fill array here
twoD = Arrays.copyOf(twoD, 2* twoD.length);
This however does not seem to work for the 2D array. How does one go about doubling the length of a 2D array. In this case to make it [20][2] instead.
A 2D array in Java is an array of arrays. For doubling it, you'll have to manually iterate over each row in the array and copy all of its columns in turn.
In your case something like this would do the job:
public static <T> T[][] copyOf(T[][] array, int newLength) {
// ensure that newLength >= 0
T[][] copy = new T[newLength][];
for (int i = 0; i < copy.length && i < array.length; i++) {
copy[i] = Arrays.copyOf(array[i], array[i].length);
// this should also work, just not create new array instances:
// copy[i] = array[i];
}
return copy;
}
And you could call this method, just like you called Arrays.copyOf()

Why 'variable can be only null at this location'?

I have this:
String data[][] = null;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
data[i][j]= "test";
}
}
But it doesn't work. Variable data is null.
Your first line should be
String data[][] = new String[10][10];
because you have to initialize your array first. Consider the array like a "pointer" in C/C++. You have to write something like String data[][] = new String[10][10];
Arrays in java are kind of objects and have to be allocated with new.
Replace
String data[][] = null;
with
String data[][] = new String[10][10];
Of course is data null, you explicitly said so. If you think that
String data[][] = null;
should initialize a 2-dimensional array and each value to null, you are mistaken.
What you need is for example:
String data[][] = new String[10][10]
this initialized a 2-dimensional array with 100 elements, that is to say: an array with 10 elements, each being an array with 10 elements.
An array in Java is an object, just like any other object, and thus has to be initialized with new. data in your example is a reference to an array which itself consists of references to other arrays (= objects).
That is because you've assigned null to it. You need to create an array and assign that to data instead. Try this instead:
String data[][] = new String[10][10];
Array assign value as a Reference type . to to asign any value in it, you have to first create instance of it otherwise it will give error. so you have to write the following :
String data[][] = new String[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
data[i][j]= "test";
}
}
String data[][] is just a reference that can hold a two dimentional string array. since you have not added any object to the reference, it points to null
so do
String data[][] = new String[10][10];
to add an object in to the reference.
you didn't initialize you array. you can define array size as per your need like given example
2d array it's like table row and column you must initialize first row size then column size
here are the example of initialization
data[][] = new String[5][]; // after this you need to define for 2d array like this
data[0] = new String[2];
data[1] = new String[3];
data[2] = new String[1];
as above the column was dynamic you define the column size as much as you want
another one is
data[][] = new String[5][3] then each row has 3 column

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