What does a method with (int[] []) mean? - java

We are given some code snippets to look at and figure out what the code does/will do.
I understand methods and methods with arrays but I have never seen methodName(int[][] m) with two [][]
What does this mean? an array within an array?

int[][] in the method signature refers to a double array of integers. You can think of a double integer array as being a matrix of int values.
Taking your example 2D array:
int[][] in = {{2, 0, 2}, {3, 1, 2}, {1, 8, 4}};
This array has the following properties:
System.out.println(in.length); // prints 3 (number of arrays inside 'in')
System.out.println(in[0].length); // prints 3 (number of ints in first array)
System.out.println(in[1].length); // also prints 3 (number of ints in second array)
Here is a visual to show you how accessing this array works:
int a = 1;
int b = 0;
Then in[a][b] == in[1][0] == 3:
2 0 2
{3 1 2} <-- a = 1 (second subarray)
1 8 4
{3 1 2}
^-- b = 0 (first element in that subarray)
The first index a chooses the subarray, and the index b chooses the element inside the subarray.

It represents multi dimensional arrays (AKA arrays or arrays) of given data type.
Think hierarchical to understand it the best way.
If you have int[3][2], it means,
It holds value for each of the following index.
int[0][0]
int[0][1]
int[1][0]
int[1][1]
int[2][0]
int[2][1]
Hope it will help. I struggled a lot to understand it when i was a beginner.
Possible assign is
int[3][2] iValue = {{00,01}, {10,11}, {20, 21}}
Thanks for the correction.

methodName(int[] []) is an array of arrays. In response to all the comments, I tested it in eclipse and the length is 3.

In many programming languages (including Java), it is possible to create (and use) an array of arrays. In Java (specifically), all arrays are Object instances. Consider
Object intArray1 = new int[10];
Object intArray2 = new int[10];
Object intArray3 = new int[10];
Then you might have
Object[] arrs = { intArray1, intArray2, intArray3 };
or even
Object arrs = new Object[] { intArray1, intArray2, intArray3 };
JLS-15.10.1 Run-Time Evaluation of Array Creation Expressions says (in part)
Otherwise, if n DimExpr expressions appear, then array creation effectively executes a set of nested loops of depth n-1 to create the implied arrays of arrays.
A multidimensional array need not have arrays of the same length at each level.
Finally, there is Arrays.deepToString(Object[]) the Javadoc says (in part)
Returns a string representation of the "deep contents" of the specified array. If the array contains other arrays as elements, the string representation contains their contents and so on. This method is designed for converting multidimensional arrays to strings.

In Java, "int [ ][ ]" stands for a 2-dimensional integer array. To make it easy to understand, simply we can compare 2-d integer array with a simple 1-d integer array;
1) Down below, a 1-d int array is initialized;
int[] arr1d = { 1,2,3 };
2) And on this one, a 2-d int array is initialized;
int[][] arr2d = { {1,2,3}, {4,5,6} };
It is important to understand the structure of 2d arrays. If you print the length of the arr2d , you will get 2 the rows of the array which is 2.
System.out.println(arr2d[].length);
You will get the length of the outer array, which is actually row count of the array.
To get the inner array length, which is actually the column count;
System.out.println(arr2d[0].length);
Notice that we take the first row, and get the length of the inner array and print the column number.
To get familiar with the usage of the 2d array in a method, you can check this out;
private static void printIntegerArray(int[][] intArray) {
for(int i = 0; i < intArray.length; i++ ) {
for(int j = 0; j < intArray[i].length; j++ ) {
System.out.printf("%3d ", intArray[i][j]);
}
System.out.println();
}
}
In this static method, int[][] intArray is the only parameter which is obviously a 2 dimensional int array. There are two nested for loops to print the array as a matrix. The outer loop is traversing the rows and the inner loop is traversing on the inner loop.
Here is the complete example for the 2D Method usage;
public class Test2DArray {
public static void main(String[] args) {
//Init 2d integer list
int simpleArray[][] = { {1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15} };
//Length of outer array which is actually Row Count;
System.out.println("Rows : " + simpleArray.length);
//Length of inner array which is actually Column Count;
//Notice that we take the first Row to get the Column length
System.out.println("Columns: " + simpleArray[0].length);
//Call the printIntegerList method with int[][] parameter
printIntegerArray(simpleArray);
}
private static void printIntegerArray(int[][] intArray) {
for(int i = 0; i < intArray.length; i++ ) {
for(int j = 0; j < intArray[i].length; j++ ) {
System.out.printf("%3d ", intArray[i][j]);
}
System.out.println();
}
}
}
And the output to the console is as below;
Rows : 3
Columns: 5
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15

Related

How to reverse slice of array java

I've been attempting to reverse a slice of a list in java.
The equivalent in python (though perhaps not the best way - I don't care about this, just want to get my point across) would be:
myList = [0,1,2,3,4,5,6,7,8,9,10]
reverseSlice = myList[2:6]
reverseSlice.reverse()
myList[2:6] = reverseSlice
When I tried to manually implement this in Java, I tried this:
public static int[] reverse(int[] x,int a1, int a2) {
a1--;
int[] rArr = new int[a2-a1+1];
for (int ind = a1; ind<a2; ind++) {
rArr[a2-ind-1] = x[ind];
}
for (int ind = a1; ind<a2; ind++) {
x[ind] = rArr[ind];
}
return x;
}
However, when I run this:
int[] cows1 = new int[]{0,1,2,3,4,5,6,7,8,9,10};
cows1 = reverse(cows1,2,6);
for (int i : cows1) {
System.out.print(i + " ");
}
I get 0 4 3 2 1 0 6 7 8 9 10 .
I'm really confused how I got this, as in my function, I don't introduce new values, so the "0" shouldn't have appeared.
My Question: Why is my code returning values that are not in the list?
The 0 value which is coming might be because of accessing an uninitialized value from rArr array. For the purpose of reversing, an extra array is not required. You can simply swap the values from the starting index to the end index. I have tested the following code and it gives correct output
public class Solution2 {
public static void main(String args[])
{
int[] cows1 = new int[]{0,1,2,3,4,5,6,7,8,9,10};
cows1 = reverse(cows1,2,6);
// both indices are inclusive
for (int i : cows1) {
System.out.print(i + " ");
}
}
public static int[] reverse(int[] x,int a1, int a2) {
for (int i = 0; i < (a2-a1+1)/2; i++) {
swap(x,a1+i,a2-i);
}
return x;
}
private static void swap(int[] x, int i, int j) {
// System.out.println("values swappeed are "+ x[i] + " " + x[j]);
int temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
and the output comes as
0 1 6 5 4 3 2 7 8 9 10
The problem seems to be the first line of your reverse function: a1--; not preserving the original value for your start index.
The method call
The purpose of the reverse function is to reverse only the portion of the array bound by variable values a1 and a2. On a side note, never use meaningless names like that. Better names for these variables could've been startIndex and endIndex or similar naming (a1 and a2 don't really mean anything).
For values (2, 6), the reverse function should extract the portion of the array starting at index 2 and ending on index 6. I am assuming the end index is not inclusive, so it should only grab values at index 2, 3, 4, and 5. However, the first thing the method does is decrement the start index, so it actually starts at index 1.
From there, the function successfully reverse the values located at these indices [4,3,2,1]. The question is now, what happens to the value at index 5? Let's see what this part of the code does new int[a2-a1+1]. The value of a2 is 6 and the new value of a1 is 1 because it was decremented in the first line. That means that your new array is of size [6-1+1] which is 6. That seems to be incorrect. Only 4 values are required to be reversed and the array is one element too big. The last index of this array is defaulted to integer value of 0.
The swap
First loop:
for (int ind = a1; ind<a2; ind++) { // starts with a1 = 1 and a2 = 6
rArr[a2-ind-1] = x[ind]; // rArr[4] = x[1]: first iteration is off by 1
}
Second loop:
for (int ind = a1; ind<a2; ind++) { // a1 = 1, a2 = 6 (starts at 1 and ends at 5 (rArr doesn't have an index 5)
x[ind] = rArr[ind]; // first iteration: x[1] = rArr[1], last iteration x[5] = rArr[5] -> this last index is accessible because array was too big and was initialized to a primitive `int` default value (0).
}
The solution
Make sure your start and end indices are preserved.
Allocate the temp array (if needed) using the original start and end indices for your calculation.
Inside the reverse() method, your first line should've been:
int[] rArr = new int[a2-a1]; // allocates an array of size 4 (6-2)
From here, if the rest of the method is wrong, you will not see a zero anywhere in the reversed array. At worst, you would've seen an offset problem if your start index was erroneously calculated. And that, I think, would've been easy to spot and fix.
If you are new at programming, and even if you are more of an "expert", you should always work out these problems on paper (or on a board) before you attempt to code and walk through your logic. You will be amazed as to how many logic errors you will catch before you code.

Why does changing one entry in a 2D array change the entire column?

//main method
int one = 1;
int[] ones = {one, one, one};
int[][] lotsofones = {ones, ones, ones};
lotsofones[0][1] = 2;
for (int[] array : lotsofones) {
for (int num : array) {
System.out.print(num + " ");
}
System.out.println();
}
/*
Expected output:
1 2 1
1 1 1
1 1 1
Actual output:
1 2 1
1 2 1
1 2 1
*/
Why is this happening? I don't understand. Why is it changing the entire column instead of just the single entry?
How do I achieve changing only one entry without initializing the 2D array differently? Is it possible?
Why is it changing the entire column instead of just the single entry?
Because each column, of each row, is the element stored in one same array object on the heap, and changing element in the array referenced with ones, will reflect that change in every other variable, which refers (or will refer) to the same array instance.
int one = 1;
int[] ones = {one, one, one}; //creates 1D array `{1, 1, 1}`
int[][] lotsofones = {ones, ones, ones}; //reuses and puts the same "ones" array, object in three indices of "lotsofones" 2D array
Therefore, changing:
lotsofones[0][1] = 2;
changes entry in ONE array object, that is referenced three times.
How do I achieve changing only one entry without initializing the 2D array differently? Is it possible?
Sure, it is. Just create 2D array by not using the same array object for every element of that 2D array. One way would look like this:
int one = 1;
int size = 3;
int[][] lotsofones = new int[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < lotsofones[i].length; j++) {
lotsofones[i][j] = one;
}
}
lotsofones[0][1] = 2; //this will now change one particular element on one 2D array, instead of changing element in an array that is re-used over and over.
Then,
for (int[] array : lotsofones) {
for (int num : array) {
System.out.print(num + " ");
}
System.out.println();
}
will output:
1 2 1
1 1 1
1 1 1

What determines the value of array.length for a 2D array?

Working in Java, suppose I have made a 2D array which is 30 by 50 units, like this:
public Array() {
int[][] array = new int[30][50];
}
and then I do this:
int rows = array.length;
int columns = array[1].length;
why does array.length get me a value of 30? Could the length not also be 50? Similarly, how then does array[1].length work out to be 50?
I have seen this answered elsewhere but I didn't understand the answer (beginner in Java here).
EDIT: This is how it was explained to me before, which I didn't understand. "when we refer to array.length, we get the length of the larger list, which is 30. When we refer to array[1].length, we get the length of the small list with index 1 in the large list, which is the second small list in the large list. This will have a value of 50."
If you rewrite to this, maybe it gets clearer
public Array() {
int[][] array = new int[30][];
array[0] = new int[50];
array[1] = new int[50];
// ... you may use a loop, but to make it explicit
array[29] = new int[50];
}
When you declare an array you MUST indicate at least the first dimension (30).
In your example all elements of the first dimension holds an array reference to an array with 50 elements.
You can have diferent lengths also:
public Array() {
int[][] array = new int[30][];
array[0] = new int[5];
array[1] = new int[7];
// ...
}
Consider this simple example
array[3][5];
array[number_of_row][number_of_column];
array[3][5] means 3*5 matrix which is
[0,0][0,1][0,2][0,3][0,4]
[1,0][1,1][1,2][1,3][1,4]
[2,0][2,1][2,2][2,3][2,4]
here you can clearly see that 3*5 matrix has 3 rows and 5 columns,
that's also means each row has 5 columns. So, array.length means
number of rows which is 3 and array[1].length means number of columns
in row position 1 which is 5
This logic is same as array[30][50]
First you need to know that a 2D array is actually a 1D array with each element in that array is another 1D array.
a[0] = [0][1][2][3]
a[1] = [0][1][2][3]
a[2] = [0][1][2][3]
a[3] = [0][1][2][3]
so length will get the length or the array being called at
i.e a.length will be the length of a, not the length of the array assigned at element 0 or 1 , ...n in a
also note the arrays created in each element of the 1D array a could be of different length. so calling a.length will not be accurate if always returned the length of 1st row i.e: a[0].length
int a[][] = new int[4][];
a[0] = new int [10];
a[1] = new int [7];
a[2] = new int [11];
a[3] = new int [30];

counting occurrence of 2d array in java

This is the question i am trying to solve:
Write a class called ArrayHistogram, which contains a main method and a static method called histogram, which has the following signature:
public static int[] histogram(int[][] arrayA)
In the main method, declare and initialize a two dimensional array, call it arrayA. This array must contain some non-negative integer numbers. The histogram method accepts arrayA and puts the frequency of occurrence of elements of arrayA into a one dimensional array (histA) and returns histA. Frequency of occurrence means, the number of times an element occurs in the array. Your program should work for a ragged array, as well. Your program should determine the size of the histA automatically, before declaring the variable histA.
Hint: Figure 1 shows a sample 2D array(arrayA) and the corresponding histA. histA[0] = 2 shows that 0 occurred twice in A. Or, histA[3] = 1, shows that number 3 appeared once in A.
I have done this so far
public class ArrayHistogram
{
public static void main (String[]args)
{
// declearing and initializing a 2D array.
int [][] arrayA = {{5,8,8,4,3},{1,4,2,2,3},{7,4,6,6,9}};
histogram(arrayA);
}
public static int[] histogram (int [][] arrayA)
{ // nested for loop to go through the array.
int max = 0;
for ( int row = 0; row<arrayA.length; row++){
for ( int col=0; col < arrayA[row].length; col++){
if ( arrayA[row][col]> max ){
max = arrayA[row][col];
}
}
}
int histA[] = new int [max];
for ( int row = 0; row<arrayA.length; row++){
for ( int col=0; col < arrayA[row].length; col++){
histA[arrayA[row][col]]++;
}
}
System.out.println(histA);
return histA;
}
}
This line:
histA[arrayA[row][col]]++;
shows a java.lang.ArrayIndexOutOfBoundsException
First am I doing this right?
If not how should I make it happen?
Keep in mind that arrays are indexed starting at 0, so your max value is not going to be an index available in your histA array. One way to fix this is create your array like so:
int histA[] = new int[max + 1];
In your second loop, when you hit row being 2 and col being 4 it's going to attempt to use histA[9] which isn't a valid index in that array unless you define your array to be of size 10, which in your case is max + 1.
length is an attribute of array objects which returns the size. Now since you are looping your array starting from 0 to the length of array, its referring to the index of array which doesn't even exists. Hence an ArrayIndexOutOfBoundException.
Just update your for loop termination expression to arrayA.length-1 and arrayA[row].length-1 and it will all be working fine.
Also for all such exceptions just check their Java Doc and you will get your answer.

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);

Categories

Resources