Java array with empty second brackets - java

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.

Related

JAVA: Creating a new array that has the same number of rows/columns in parameter?

I'm having a bit of trouble understanding how arrays work, specifically when the array is not given a specific size. For example, if I'm given the code:
public int [][] someMethodHere(int [][] myNewArray) {
//code here
}
I want to know how I can create another array within the method with the same number of rows and columns in the parameter (WITHOUT just adding in some numerical value in the parameter and then just writing the same value in the new array. Thanks!)
An array has a fixed size that you set when you create the array.
This is different to many other data structures like List or Map that are "smart" and can handle resizing themselves when the need arises.
So when you create an array you must tell the compiler how big it is:
// create the original array with 10 slots
int[] originalArray = new int[10];
If you want to create a new array of the same size, you can use the length property of the Array type.
// create a new array of the same size as the original array
int[] newArray = new int[originalArray.length];
In your case of a 2-dimensional array, you could do it like this:
// create the original array
int[][] originalArray = new int[10][20];
// create a new array of the same size as the original array
int[][] newArray = new int[originalArray.length][originalArray[0].length];
Notice that when specifying the length of the second dimension, I get the length of the first element in the original array. This works as long as all the rows have the same length.
If the rows are of different length you could set the length of each row in the new array by iterating over the first dimension of the array like this:
// create a new array where the first dimension is the same size as the original array
int[][] newArray = new int[originalArray.length][];
// set the size of the 2nd dimension on a per row basis
for(int i = 0; i < originalArray.length; i++) {
newArray[i] = new int[originalArray[i].length];
}
You can make a copy of the array and clear the new array.
public static int[][] someMethodHere(int[][] src) {
int length = src.length;
int[][] target = new int[length][src[0].length];
for (int i = 0; i < length; i++) {
System.arraycopy(src[i], 0, target[i], 0, src[i].length);
Arrays.fill(target[i], 0);
}
return target;
}

Converting ArrayList<Integer> into int[] won't work in Java

I have been developing a program where I have to convert an ArrayList into an int[]. I do not get any syntax errors when I run the code. However, when I print the int[] to see if it does work, it prints out a random string which is "[I#2a139a55" How can I fix this?
I cannot use an int[] from the start. This program HAS to convert an ArrayList into int[].
ArrayList<Integer> student_id = new ArrayList<Integer>();
student_id.add(6666);
student_id.add(7888);
int[] student_id_array = new int[student_id.size()];
for (int i=0, len = student_id.size(); i < len; i ++){
student_id_array[i] = student_id.get(i);
}
System.out.println(student_id_array);
You are printing out the reference to the array. Use Arrays.toString(int[]).
You can do the converting your ArrayList<Integer> to int[] with one line in Java 8:
int[] student_id_array = student_id.stream().mapToInt(id -> id).toArray();
And if you want to output array's values instead of representation of your array (like [I#2a139a55) use Arrays.toString() method:
System.out.println(Arrays.toString(student_id_array));
That because you are printing the memory address of that array.
try this :
ArrayList<Integer> student_id = new ArrayList<Integer>();
student_id.add(6666);
student_id.add(7888);
int[] student_id_array = new int[student_id.size()];
for (int i=0, len = student_id.size(); i < len; i ++){
student_id_array[i] = student_id.get(i);
}
System.out.println(student_id_array[0]+" "+student_id_array[1]);
Output :
6666 7888
OR use for-loop if you populate the ArrayList later on.

How to trim out an array of integers in Java?

Let's that I have a number N. N will be the size of the array.
int numArray [] = new numArray[N];
However, the contents of the array will hold every other number from 1 to positive N. This means that the entire size N array will not be full after that for loop. So after the for loop, I want to trim (or resize) the array so that there will no longer be any empty slots in the array.
Example :
Let's say N = 5;
That means, after the for loop, every other number from 1 to 5 will be in the array like so:
int arr[] = new int[N];
int arr[0]=1;
int arr[1]=3;
int arr[2]= null;
int arr[3]= null;
int arr[4]= null;
Now, I want to trim (or resize) after the for loop so that the indexes that hold null will be gone and then the array should be:
int arr[0]=1;
int arr[1]=3;
The size of the array is now 2.
You can't trim an array. The fastest approach is just to copy it into a smaller one, using System.arraycopy, which is almost always much faster than a for loop:
int somesize = 5;
int[] numArray = new int[somesize];
//code to populate every other int into the array.
int[] smallerArray = new int[somesize/2];
//copy array into smaller version
System.arraycopy(numArray, 0, smallerArray, 0, somesize / 2);
You can't change the size of an array in Java after it has been created.
What you can do however, is to create a new array of the size that you need.
Another important point is that you are creating an array of a primitive: int. Primitives are not objects and you cannot assign the value null to a primitive.
You need to create an array of java.lang.Integer if you want to be able to set entries in it to null.
Integer[] numArray = new Integer[N];
Thanks to a Java feature called auto-boxing, almost all code that works with primitive int values, also works with Integer values.
Steps:
Use Integer[] instead of int[]
Calculate the size that you need (count non-null entries in original array)
Allocate a new array of the size that you need
Loop over the old array, and copy every non-null value from it to the new array.
Code:
Integer[] oldArray = ...;
// Step 2
int count = 0;
for (Integer i : oldArray) {
if (i != null) {
count++;
}
}
// Step 3
Integer[] newArray = new Integer[count];
// Step 4
int index = 0;
for (Integer i : oldArray) {
if (i != null) {
newArray[index++] = i;
}
}
I think there is a bit shorter way to do the trimming itself.
Whats left is to find the proper index.
You can do:
int someIndex = Arrays.asList(arr).indexOf(null);
arr = Arrays.copyOfRange(arr,0,someIndex);
You surely better of with some more appropriate data structure, for example a list or a set depending on what's your intention with it later. That way you don't even need to create an N sized structure just so you'd have to reduce it anyway. Rather you create an empty list and add the elements that you actually need
import java.util.Arrays;
public static void main( String[] args )
{
int[] nums2 = {9,4,1,8,4};
nums2 =Arrays.copyOf(nums2,3);
for (int i : nums2) {
System.out.print(i+" ");
}
}
//Output
9 4 1

Number of columns in 2d array declaration

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

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

Categories

Resources