Trouble understanding Multidimensional Arrays - java

So i am trying to understand multidimensional arrays a little better. So far, I understand there are 2 way to construct these arrays. One is
int[][] b = { { 1, 2 }, { 3, 4, 5 } };
The first array constructs row 0 with 2 columns ( column 0 and column 1). What i don't understand is why are these numbers chosen. Does it always have to be in numerical order, or do the numbers mean something more? If i were to create a new row would it start with 6? Would it just be better for me to construct it this way?
int[][] b = new int [2][];
b[0] = new int [2];
b[1] = new int [3];
Thanks for your help.

Those numbers are meant to be examples. You need not start your next row with "6" if it's not what your solution demands.
Either manner of construction is acceptable. You'd use the second one if you had to compute the values and didn't know them beforehand.

1, 2, 3, 4, and 5 are just data that got entered in this new array.
The array would look like this:
[
[1, 2]
[3, 4, 5]
]
so [0][0] = 1; [1][0] = 3, [1][2] = 5 etc
Those values are just chosen as example.

First: there is no multi-dimensional arrays in Java. There are only arrays containing arrays. Arrays of arrays if you prefer.
int[][] b = { { 1, 2 }, { 3, 4, 5 } };
constructs an array containing 2 arrays of int. The first array contains the numbers 1 and 2, and the second contains the numbers 3, 4 and 5. These numbers could be anything you want. The line declares and populates the array at the same time.
int[][] b = new int [2][];
b[0] = new int [2];
b[1] = new int [3];
constructs an array of arrays of ints, containing two null elements. Then, the first element of the outer array is initialized with an array of 2 ints, and the second element of the outer array is initialized with an array of 3 ints. All the ints are initialized to their default value: 0.

Related

2D Array where each element is a List

I'm trying to write a program where I have a 2D array, stored_variables[][], where each element of stored_variables is a list rather than a normal element. I know how to make a 2D array of lists, but not how to do this.
You just create your 2D array, and put another array inside each field. So basically you end up with a 3D array:
int[][][] arr = {
{
{1, 2, 3},
{4, 5, 6}
},
{
{7},
{8, 9},
{10}
}
};
Now you have an Array, that contains 2 Arrays. And the first of those 2 Arrays contains another 2 Arrays (with 3 values each). And the second one contains 3 Arrays (with 1, 2 and 1 values).

How to merge arrays in alternating pattern without duplicates

I'm currently learning in school but am unable to complete this part of the assignment.
An explanation with the use of for loops would be greatly appreciated.
The numbers should be added to the merged array in an alternating pattern: first from list 1, then from list 2, then list 1 again, etc. If a number in one of the arrays already appears in the merged array, then it should be ignored, and the program should alternate to the other list again. For example, if the first list begins 1 2 3 10, and the second begins 3 4 5 8, then the merged list would begin 1 3 2 4 5 10 8.
Because the number of elements in the merged array is unknown, its size should be set to the maximum possible number of elements it should contain, and after all elements which should form the merged array appear, any remaining unfilled spaces in the array should be 0. The first 0 encountered in the array should signal the end of the “actual” elements of the array, and therefore the 0s at the end of the array should not be printed by your program.
I propose to use a HashSet to remember which number you have already inserted into the array. For each number, you first check if the hash set already contains the number; if not, you add it to both the array and the set. For large inputs, this is much faster than checking the result array for each number. O(n*log(n)) or so (depending on how well the HashSet works for your input) instead of O(n^2).
#bubble
An example using a Set is very simple - however your teacher is asking for
an alternate list:
Integer[] one = new Integer[] {10,2,3,1};
Integer[] two = new Integer[] {3,8,5,4};
List<Integer> li_one = Arrays.asList(one); // First convert the arrays to a list
List<Integer> li_two = Arrays.asList(two);
Set<Integer> set = new HashSet<>();
set.addAll(li_one);
set.addAll(li_two);
System.out.println("The unique list is: " + set);
A HashSet was my first idea too, but the order of storing values depends
one hash values. The ... teacher likes to have alternating values which
I dont like to comment - because it is a really strange request.
Following code prints: merged list is: [1, 3, 2, 4, 5, 10, 8]
int[] one = new int[] {1,2,3,10};
int[] two = new int[] {3,4,5,8};
int one_len = one.length;
int two_len = two.length;
List<Integer> merged = new ArrayList<>();
int oneval,twoval;
for (int i = 0;i < one_len;i++)
{
oneval = one[i];
if (!merged.contains(oneval)) merged.add(oneval);
if (i < two_len)
{
twoval = two[i];
if (!merged.contains(twoval)) merged.add(twoval);
}
}
if (two_len > one_len)
{
for (int i = one_len; i < two_len;i++)
{
twoval = two[i];
if (!merged.contains(twoval)) merged.add(twoval);
}
}
System .out.println("merged list is: " + merged);

Can the size of an N-dimensional array change in Java?

An array in Java is an object. So if I have a 2D array double[][] matrix = new double[5][5] then each row of that array is an object referencing a single dimensional array in memory. From my understanding, once the array size is set in java it can not be changed. So let me declare a 1D array double[] d = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} I am then allowed to set matrix[1] = d so that row 1 is now pointing to d in memory. I seems like the array size is not really fixed. I can declare matrix to be of any size and just change the reference to point to an array of a different size. Why am I allowed to do this if the matrix size is fixed to be 5 x 5 ?
The assignment
double[][] matrix = new double[5][5];
actually creates 6 array objects. One array whose element type is double[] (i.e. an array of double arrays) having a length of 5 and referenced by the matrix variable, and 5 arrays whose element types are double having a length of 5 and references by matrix[0]...matrix[4].
Just as you can change the matrix variable to refer to a new array by assigning :
matrix = new double[10][10];
you can also change any of the references matrix[i] to refer to a new array by assigning :
matrix[i] = new double[6];
You are not changing any existing array. You are changing the value of a reference variable which referred to one array to refer to a different array.
Simply spoken: because that is how the fathers of Java made arrays work.
And the syntax gives a hint there:
double[][] matrix = new double[5][5]
You see, the 5,5 only shows up on the right hand side! Meaning: the array dimensions are not part of "type" of matrix!
The key thing is: there are no true "multi dimensional" arrays in Java. There is no way to say: this thing should be "5 x 5". You always end up with an array of "rows"; and each row contains an array of columns. And therefore, those columns can have different lengths,as they are completely independent of each other!

please help me out its very confusing java code

public class Test {
public static void main(String[] args) {
int arr[] = {1,2,3,4};
int i=0;
while (i<20)
{
System.out.println(arr[?]);
}
}}
what should we write in place of ? so that ArrayIndexOutOfBounds exception do not occur and the output is as follows?
1
2
3
4
1
2
3
4
1
2
3
4
1
2
3
4
1
2
3
4
Use modulu 4, since that would give you integers between 0 and 3, which are the indices of your array :
System.out.println(arr[i%4]);
But don't forget to increment i.
int arr[] = {1,2,3,4};
int i=0;
while (i<20)
{
System.out.println(arr[i%4]);
i++;
}
A more succinct solution (though less readable in my opinion), would be to combine the two statements :
System.out.println(arr[(i++)%4]);
You want the array index to always be one of {0, 1, 2, 3}.
The mod n (%n) operation will get you result among [0, n-1].
So you can write it like:
System.out.println(arr[(i++)%4]);
With this solution one can vary the length of the array. And 'i' can take any value. So that Array Index Out Of Bound exception do not occur.
System.out.print(arr[i++%arr.length]);

initializing a 2d array in JAVA

If I declare a 2d array, for example:
int[][] numbers = new int[5][];
I thought that you had to individually declare/initialize each of the 5 int[]?
For example, before I assign a value to numbers[0][1], I would have to say:
numbers[0] = new int[4];
I wrote a small program and explicitly put a value in numbers[0][1], ran it, and it worked without initializing numbers[0] first.
Am I completely off thinking that the individual arrays have to be initialized first in a 2d array?
Edit: My misunderstanding was in the initialization. The 1st 2 statements are ok, because I declared the length of each int[] in goodArray to be 3, which causes all of them to be initialized. Whereas in the badArray declaration, I only declared how many arrays there were(3), so I get a npe:
int [][]goodArray = new int[3][3];
goodArray[0][1] = 2;
int[][] badArray = new int[3][];
badArray[0][0] = 2;
With multidimensional arrays in Java, you can specify a position, there is no need to individually define them.
You can easily test the behavior of the 2D arrays using examples like the one below:
int[][] numbers1 = new int[][] { {1, 2, 3}, {1, 2, 3, 4, 5}}; /* full initialization */
numbers1 = new int[3][]; /* [3][0] is null by default */
try {
System.out.println(numbers1[0][0]);
} catch (NullPointerException e) {
System.out.println(e);
}
numbers1[0] = new int[3]; /* all three ints are initialized to zero by default */
System.out.println(numbers1[0][0]);
numbers1[0] = new int[] {1, 2, 3};
System.out.println(numbers1[0][0]);
Will produce the following output:
java.lang.NullPointerException
0
1
int[][] numbers = new int[5][];
With the previous line you have created 5 int[] one dimensional array. Now you need to say the size for each one dimension array before you use them. Java gives this flexibility ao that you can have variable size one dimensional int [] arrays inside 2D array.

Categories