Java native array lengths - java

I have a 2D array of doubles in Java which is basically a table of values and I want to find out how many rows it has...
It is declared elsewhere (and allocated) like this:
double[][] table;
then passed to a function...
private void doSomething(double[][] table)
{
}
In my function I want to know the length of each dimension without having to pass them around as arguments. I can do this for the number of columns but don't know how to do it for the rows...
int cols = table[0].length;
int rows = ?;
How do I do that?
Can I just say...
int rows = table.length;
Why would that not give rows x cols?

In Java a 2D array is nothing more than an array of arrays.
This means that you can easily get the number of rows like this:
int rows = array.length;
This also means that each row in such an array can have a different amount of elements (i.e. each row can have a varying number of columns).
int columnsInFirstRow = array[0].length;
This will only give you the number of columns in the first row, but the second row could have more or less columns than that.
You could specify that your method only takes rectangular arrays and assume that each row has the same number of columns than the first one. But in that case I'd wrap the 2D-array in some Matrix class (that you might have to write).
This kind of array is called a Jagged Array.

Look at this example. They use .length there to get the row count, [].length to get the column count.
It's because the array consists of "row" pointers and these could lead anywhere, so you have to use .length for each column to get the sizes of these arrays, too.

I don't quite understand your question. You have to realize that in Java, multidimensional arrays are in fact arrays of arrays.
table.length will in fact give you the number of one-dimensional arrays contained in your two-dimensional array (assuming there are no null entries).
table[0].length will give you the size of the first one-dimensional entry. This could be different from the size of the others, and it could throw a NullPointerException (though neither is possible when it's allocated as new double[rows][cols]).

Well, first of all, why don't you just test if
int rows = table.length;
gives the desired result?
It does indeed give you the number of elements in the first dimension. Multidimensional arrays are in fact nothing special, as they are just arrays of arrays of arrays of ... In your case - a 2D array - it is organized like this (in pseudo-code):
double[][] foo = { double[] = {...}, double[] = {...}, ... }
So when accessing foo, it refers to the "outer" array, which has of course the length property, which contains the number of arrays it contains on the second level.
You can read the double[][] as "An array ([]) of double-arrrays (double[])".

No it won't. You can just use table.length

Alternatively, you could wrap your 2d array into a Matrix or Grid class of some sort. Internally, you could represent it as a 1d array and compute offsets for the row/col coordinates.

Related

How can I expand the entries of a 2d array in Java?

How can I dynamically allocate space for n entries, if I already know the number of columns of a 2d array? I wanted to know the way to doing this without using Lists but I cannot find anything. Any help?
Try this.
int rows = 200;
int cols = 300;
int[][] mat = new int[rows][cols];
You can also read in the row and col from a file, allocate your array and then continue reading the values to populate the array.
The difficulty comes when you don't know the size of the array. So you need to first, pre allocate the array which is a guess. Then read in as much as you can and continually increase the size until you are done reading.
You can use Arrays.copyOf() function.
Let's say you want to increase size of 4th row in your 2d array with 6 rows.
you could simply, say myArray[3] = Arrays.copyOf(myArray[3], newSize);

User defined Array dimensional and size

I have unsolvable task, I have task, where i have insert random number to array. The user can choose if array is 1D, 2D, 3D,size of array is optional . I tried everything but withot success. I can not use ArrayList.
Thank you for help.
double[] array= new double[size];
for ( int i;i<dimensional;i++)
{
double[] array= new double[size];
}
Edit:
I mind if is effective way to create array with 1D and then add to this array one or more dimension.
Multi-dimensional arrays in java are essentially just arrays of arrays. The user provides the number of dimensions and sizes at runtime so you need to dynamically build this array at this point. It's a strange problem, and not one that you would try to solve with arrays in production code, but nevertheless it should be possible. Try the accepted answer for this question, it seems like a pretty good attempt.
So, an "unsolvable" task ... well, as long as you work with primitive types and the dimension can be theoretically any number (only limited by memory available), you may be right.
You can however use some kind of object (Java is an object-oriented language) and solve the task rather easily. Basically, you might want a tree structure with nodes. You can even write a constructor that sets fixed sizes for every level and give no direct accessors to the array as a whole. Start with:
class Node {
double payload;
Node[] children;
}
I don't really understand what do you want to do with that, but it pretty much fits the idea of N-dimensional array.
Another solution: Make the array one-dimensional, but using the sizes of the individual dimensions, you can calculate the correct index. Of course, it will require you to handle the logic.
E.g. in a 2D array of 3x3 size, you can use a 1D array of 9 size and use first three indexes for first row, next three for second row, last three for third row. You can then use a cycle like this:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
//arr[i * 3 + j] = ...
}
}

Selectively allocate dimensions for multi-dimensional array at construction

Java supports multi-dimensional arrays, which are represented as "arrays of arrays". For instance, I can create an array of String arrays using the following code:
int rows = ...
int cols = ...
String[][] array2d = new String[rows][cols];
What I'd like to do is have the second dimension be "nulled out". In other words, a for-loop like for(String[] array : array2d) System.err.println(array); would print out:
null
...
null
The reason I'd like to do this is because I have already allocated a bunch of String[] instances that I want to just drop into array2d. I have a couple of solutions but both seem sub-optimal for the following reasons:
Solution 1
I could just do something like String[][] array2d = new String[rows][0], use a for-loop to null out the first dimension, and populate the rows later, but this seems ugly to me because Java will create a new empty String[] for every row, and I really don't need it to.
Solution 2
I could also do something like String[][] array2d = new String[][]{null, null, ... null}, but this is even worse because I have to hard code the length of the first dimension of array2d via the bracketed section of code, which is disgusting.
I recognize that this isn't a huge problem, especially when the dimensionality is small, and any programmer worth his salt would choose some other construct over creating arrays of many dimensions. I'm mostly just curious if there is a way to partially allocate dimensions of a multi-dimensional array at construction.
Easiest solution possible:
int rows = ...
String[][] array2d = new String[rows][];
If you don't initialize the second dimension, you array will have null entries in dimension 1.

Array of Lists or Other Possibilities?

So my question starts out as being is it possible to make an array of linked lists in Java?
For some background on why I am asking. I am working on a project in which we are given a file of square matrices. We have to find the determinant of the matrices but they have to be stored in a linked structure. We have previously done this same thing using arrays and so I can reuse a decent bit of my source from that one. Here is what I have though up to do (mostly based on my previous project):
Read each line of the file in as a string
Count the number of matrices and determine where each starts and ends.
* Read each element of each matrix into a multi-linked ListNode (I'll write the class for those)
* Repeat for each matrix
Process the determinant of each.
So the two starred steps are the ones I'm having a tough time figuring out. I want to read in all the matrices at once so I don't lose track of where I am in the file like I would if I read in one matrix, did the determinant, and then went back to the file to get another one. However, I don't know how to store each linked list representation so that I can just iteratively process through each. My only thought is to read each matrix into the linked list structure and store each linked list structure in an array if possible. If not possible, what is a possible alternative?
It is entirely possible to store an array of LinkedLists; arrays can be applied to objects as well as primitive types. However, I would advise creating a Matrix class, because square matrices are not linked lists; they have data in two dimensions, not just one. At the very least, you could use a two-dimensional array of floats to represent a matrix, and store a LinkedList of double[][]s. The closer your representation is to the actual object, the easier it will be for you.
If you are allowed to use the standard LinkedList class what java already has, the here is a possible implementation of reading, and storing your matrices:
int size = 10; //width and height of your matrix.
LinkedList<LinkedList<Integer>> matrix = new LinkedList<LinkedList<Integer>>();
for (int i = 0; i<size; i++)
{
LinkedList<Integer> list = new LinkedList<Integer>();
for (int j = 0; j < size; j++)
{
//read the actual item
}
matrix.add(list);
}
For reading a matrix (probably numbers) i advise to use the class called Scanner. You can create a new Scanner, what will be able to read your file, number by number:
Scanner sc = new Scanner(new File("input.txt"));
And you can read integer values with it, without any conversion like this:
int x = sc.nextInt();
You can make an array of linked lists in Java by declaring LinkedList[], but if you do, your performance will suffer badly. A look at matrix multiplication will illustrate the reason.
If A and B are matrices where the A's column count equals B's row count, then A * B[r, c] is the dot product of row r in A with column c in B. This means we have to extract rows and columns from our matrices.
If we form matrices from lists (of any sort), we can store them row-wise (i.e., where the 0-th list represents row 0), or column-wise (where the 0-th list represents column 0).
Now we run into a problem. In a linked list, the method get(n) starts at the beginning of the list and finds the next member n times -- which makes it run in order n time. A matrix built from linked lists will either extract columns very slowly (if stored row-wise), or extract rows very slowly (if stored column-wise).
I's suggest keeping it simple by using arrays of arrays. You can allocate an n x n array with
int[][] values = new int[n][n];
The value 'n' must be defined, of course.
Hope that this helps.

Test length of multiple dimensions of an array in Java

I'm a Java noob. I don't know very much about the language (at least, not enough to do complex things) right now, but I'm getting there!
I know you can test the length of a single-dimensioned array by doing arr.length, but is it possible to test other dimensions (in a multidimensional array)?
Yes, it is. Obviously, to test the first dimension you would just do arr.length. Subsequent dimensions are tested by using length with the [0] element of that particular dimension. For example, consider this array:
int[][][][] arr = new int[10][11][12][13];
To test the...
first dimension: arr.length;
second dimension: arr[0].length;
third dimension: arr.[0][0].length;
fourth dimension: arr.[0][0][0].length;
A multidimensional array is just an array of arrays, and each array in the array can have different lengths. I.e.:
int arr[][] = new int[2][];
arr[0] = new int[5];
arr[1] = new int[10];
System.out.println(arr.length);
System.out.println(arr[0].length);
System.out.println(arr[1].length);
Now you have a two-dimensional array. The first dimension (outer) can be referred to as arr and is of size 2. The inner arrays can be referred to as arr[0] and arr[1] and have lengths 5 and 10, respectively. Since each of these refers to a normal Java array, you can use all the normal ways of accessing an arry on them. Further, since we create multidimensional arrays by putting arrays in arrays, you can have as many dimensions as you want, and you access each further level down by indexing into the one above: arr[2][1][5][11][3][0][123][5][42][9][7]....length
Given, say, a 2D array, you can access the length of the ith inner array with arr[i].length.
If you haven't already seen it, check out Arrays (The Java™ Tutorials).
You can test the other dimensions of the other dimensions by directly referrencing the dimension you are wanting to test.
For example, if you have a 2 dimensional array with 3 items in the primary dimension then you can identify the length of each of them by using arr[0].length, arr[1].length, and arr[2].length.
the code below just sets up an array, and then verifies that the lengths are what we expect them to be.
public void testLength(){
//setup the array you are wanting to test
int[][] foo = new int[2][5];
// this just makes sure that we do get 2 dimensions within the primary
Assert.assertEquals(2,foo.length);
Assert.assertEquals(5,foo[0].length);
// change the array stored within foo[0]
foo[0]= new int[8];
Assert.assertEquals(8,foo[0].length);
}

Categories

Resources