How to Initialize 2d ArrayList with 0 in one line - java

How to Initialize all the element of 2d Array List in Java with 0 in single line of code without using for lop.
ArrayList of m rows and n columns.
How to initialise value of all the elements to 0 at the time of defining it.

Not sure what you meant by 2D ArrayList, but you returned type of List instead of ArrayList with help of below:
List<List<Integer>> a=Arrays.asList(Arrays.asList(0));
For normal arrays you can do something :
int[][] b=new int[1][2];

Related

Increasing Array Index without using Arraylist or Copying Elements over to another Array

I have an assignment for class that requires increasing the size of an arrays index.
The instruction mentions not to create a new array and copying the elements, calling it rather inefficient. Instead they suggest the following
"A more common strategy is to choose an initial size for the array and add elements until it is full, then double its size and continue adding elements until it is full, and so on."
I'm having trouble wrapping my head around this. How would I got about accomplishing this?
You can double the size of an array if you multiply the lenght of your current array, like this:
array = Arrays.copyOf(array, array.lenght*2);
You have to create a new array or you can do something like :
int a[] = new a[10];
a = Arrays.copyOf(a, a.length + arrayGrowNumber);
In above example you are just copying your existing array to a new array defined with large size array.
For more information please visit this link.
Initial size for the array and add elements until it is full, then
double its size and continue adding elements until it is full, and so
on.
This is statement clearly shows to use java ArrayList as this strategy is used in ArrayList.
This is how it is declared.
List<Your_DataType> lst=new ArrayList<>();
e.g.
List<Integer> lst=new ArrayList<>();
lst.add(1);
lst.add(2);
lst.add(3);
lst.get(0);// shows 1 which is at 0th location
lst.get(1);// shows 2 which is at 0th location
lst.get(2);// shows 3 which is at 0th location
Your instructions are conflicting. The "common strategy" instructions will still "create a new array and copying the elements", but will do so less often.
Say you create the array at size 20, then begin adding a total of 50 values.
After adding first 20, you create a new array of size 40 and copy values over, then continue adding to the new array.
After adding 20 more (total of 40), you create a new array of size 80 and copy values over, then continue adding to this new array.
When you've added all 50 values, you have an array of size 80, with values in the first 50 positions. You've copied the array twice.
Saying that you cannot create a new array is misleading/wrong. You have to. The "common strategy" instruction of "double its size" requires it.

How to calculate the number of elements in multidimentional arrays?

i've had this question ever since i learned two dimensional arrays... and i hope someone can clarify things for me..
here's what i know
int[] x= new int[2];
this one dimensional array has two elements.
int[][] y=new int[2][3];
this two dimensional array has six elements right? (2 x 3 = 6)
but when i look into the way a two dimensional array is actually made,
first a reference type variable named y that can store memory
addresses of a two-dimensional array is made in the stack.
then an object with two elements that can store one dimensional
memory addresses is made in the heap.
then another 2 one-dimensional arrays are made, each consisting 3
elements that can store int type values. and the memory addresses of
these two one dimensional arrays are assigned to the two elements
that were made earlier inside the object.
then this object's memory address is assigned to the y variable that
is in the stack.
now the problem i have is, only two elements are made inside that object in the beginning right? so doesn't that mean that the two dimensional array has two elements. and the two one-d arrays have 3 elements each?
all of these questions bugs me because y.length = 2 and y[0].length =3
please correct me if i am wrong and hope someone could help me. thanks
Yes, you're absolutely right. Java doesn't have 2-dimensional arrays per se. All it has is arrays containing arrays, and syntax sugar (new int[2][3]) to create them.
But you could indeed have an array containing arrays of different lengths:
int[][] array = new int[2][];
array[0] = new int[5];
array[1] = new int[3];
System.out.println(Arrays.deepToString(array));
// prints [[0, 0, 0, 0, 0], [0, 0, 0]]
So it you get an int[][] and want to know how many integers it contains, you need to loop through the outer array and sum the lengths of the inner arrays. Unless you have the guarantee that all inner arrays have the same length. In that case, you can multiply the length of the outer array by the length of any of the inner arrays.
In Java, multidimensional arrays are actually arrays of arrays. For example, a two dimensional array variable called arr looks like:
int arr[][] = new int[4][5];
This allocates a 4 by 5 array and assigns it to arr. Conceptually, this array will look like the one shown in the Figure:
When you allocate memory for a multidimensional array, you need only specify the
memory for the first (leftmost) dimension. You can allocate the remaining dimensions separately. For example:
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
While there is no advantage to individually allocating the second dimension arrays in this situation, there may be some benefits. Like allocating dimensions manually, you do not need to allocate the same number of elements for each dimension. As stated earlier, since multidimensional arrays are actually arrays of arrays, the length of each array is under your control.
You could flatten your multidimensional Array with this method, and call List#size() on it.
It will even flatten nested Lists, Sets, Maps and Queues.

declaring a column length of 0 in a 2d array

I was just wondering if it was legal to declare a 2d ragged array with one or more of the columns having a length of 0. If it was legal, what will it actually do?
The answer is yes, it is possible. But then there's another question, why would you consider doing this? The reason I ask this is think about what you're trying to do here. An array in which the columns are of length 0 is technically an empty 2D array. I will, however, show how to do what you're asking and what will happen.
int[][] arr = new int[2][0]; //initializing a 2x0 array, which is 2 rows of size 0
or if you're trying to make a jagged array
int[][] arr = { {},{2} }; //this is a 2d array in which the first row has zero columns and the second row has one column
But what happens when you try operating on this array? You surprisingly won't get a compiler error, but you will get a runtime error. Suppose I added this line of code and tried running the program,
arr[0][0] = 1;
The error I would get is this,
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
because I can't access any elements in a 2d array with columns of size 0.

How to Correctly Create a Set of a Multi-Dimensional Array

I have been looking through the Java Tutorials at the Interfaces tutorial, specifically on Collections (Set, List, Queue, etc.) and I came across the fact that a Set cannot contain duplicates in its elements.
My problem is the fact that I do not fully understand how to create a set of a multi-dimensional array of an unknown size.
In order to fill the multi-dimensional array, I will be placing 1's and 0's inside of an array so that each one will look like the following: (if it fits the criteria I am looking for)
[ 0 1 1 0
0 1 1 0
0 1 0 0
0 1 0 0
0 0 0 0 ]
Or something of that nature. I would like to think this can be accomplished through declaring an multi-dimensional array like:
int[][] array = new int[5][];
Yet I cannot understand how that would work with filling multiple array elements or how to accomplish this with a set.
Please let me know if this is not clear enough.
List's can contain duplicates, sets cannot. You can declare a (dynamic) multidimensional structure in several ways, heres one:
List<List<Integer>> multiDimensional = new ArrayList<List<Integer>>();
List<Integer> row = Arrays.asList({0, 1, 1, 0});
multiDimensional.add(row);
And so on and so forth. To access the elements of the list utilize the get method in a way similar to what you would do with arrays:
Integer someVal = multiDimensional.get(0).get(3);
Having said that, you only need to use this nested List setup if your multidimensional structure needs to be 100% dynamic, aka you need the ability to grow the rows and columns constantly throughout the execution of your logic. You can actually use an ordinary array for your multidimensional structure, assuming that the number of rows can be determined ahead of time, and that each row's length will not change after that row has been initialized. Case in point:
int[][] multiDimensional = null;
int rows = ... ;// Determine number of rows
multiDimensional = new int[rows][];
for(final int[] row: multiDimensional) {
final int cols = ...; // Determine number of cols for this row
row = new int[cols];
}
And you access the elements with your usual array semantics (multiDimensional[0][3]).

How to ask 2-dimensional Java array for its number of rows?

How should I go about asking a 2-dimensional array how many rows it has?
Firstly, Java technically doesn't have 2-dimensional arrays: it has arrays of arrays. So in Java you can do this:
String arr[][] = new String[] {
new String[3],
new String[4],
new String[5]
};
The point I want to get across is the above is not rectangular (as a true 2D array would be).
So, your array of arrays, is it by columns then rows or rows then columns? If it is rows then columns then it's easy:
int rows = arr.length;
(from the above example).
If your array is columns then rows then you've got a problem. You can do this:
int rows = arr[0].length;
but this could fail for a number of reasons:
The array must be size 0 in which case you will get an exception; and
You are assuming the length of the first array element is the number of rows. This is not necessarily correct as the example above shows.
Arrays are a crude tool. If you want a true 2D object I strongly suggest you find or write a class that behaves in the correct way.
Object[][] data = ...
System.out.println(data.length); // number of rows
System.out.println(data[0].length); // number of columns in first row
int[][] ia = new int[5][6];
System.out.println(ia.length);
System.out.println(ia[0].length);
It depends what you mean by "how many rows".
For a start, a 2-dimensional array is actually a 1-D array of 1-D arrays in Java. And there is no requirement that a 2-D array is actually rectangular, or even that all elements in the first dimension are populated.
If you want to find the number of elements in the first dimension, the answer is simply array.length.
If you want to find the number of elements in the second dimension of a rectangular 2-D array, the answer is `array[0].length.
If you want to find the number of elements in the second dimension of a non-rectangular or sparse 2-D array, the answer is undefined.

Categories