Array assignment vs. for loop assignment - java

In a class I have a private array
private boolean[][][] array;
that is later declared as
array = new boolean[2][100][100]; //*
At a certain point I want to overwrite the first array in the first dimension with the second array of the first dimension. I assumed this should work
array[0] = array[1];
but this yielded wrong behavior. I tried this plain for-loop:
for (int column = 0; column < array[0].length; column++) {
for (int row = 0; row < array[0][0].length; row++) {
array[0][column][row] = array[1][column][row];
}
}
and it worked as expected.
Why didn't the first snippet of code work?
*The first dimension is static at 2 but the other actually come from another array. I removed them for clarity.

The first snippet of code did not work because it does not copy the array dimension, it aliases it. Arrays are objects, so the assignment creates a second reference to the same dimension, and assigns it to the first dimension. That is why you get a different (and incorrect) behavior.
Here is an illustration of what is going on:
The assignment drops the 100x100 array from the top dimension at index zero, and replaces it with a reference to the 100x100 array at dimension 1. At this point any modification to the first array get reflected in the second array, and vice versa.
If you do not care about keeping the prior version of the array after re-assignment, you can assign a brand-new array to element 1, like this:
array[0] = array[1];
array[1] = new boolean[100][100];

This line
array[0] = array[1];
States that the object reference stored in array[1] will be now also stored in array[0]. Since an array in Java is an object reference, now both array[0] and array[1] point to the same location.
If you want/need to clear the data of an array, use a loop: for, while, do-while, the one you feel more comfortable.

Well, i don't think that you can perform copy or even a simple call unless you address you array in "proper way".
So something like
array[0]=array[1];
or
array[0][1]=array[1][1];
won't work but if you write
array[0][0][0]=array[1][0][0];
it will work, i'm guessing because the compiler is sure you are talking about the same array here.

Related

What is the time complexity of the add and element in a Java Array?

Hello I am research about that, but I cannot found anything in the oracle website.
The question is the next.
If you are using an static Array like this
int[] foo = new int[10];
And you want add some value to the 4 position of this ways
foor[4] = 4;
That don't shift the elements of the array so the time complexity will be O(1) because if you array start at 0x000001, and have 10 spaces, and you want put some in the x position you can access by (x*sizeOf(int))+initialMemoryPosition (this is a pseudocode)
Is this right, is this the way of that this type of array works in java, and if its time complexity O(1)
Thanks
The question is based on a misconception: in Java, you can't add elements to an array.
An array gets allocated once, initially, with a predefined number of entries. It is not possible to change that number later on.
In other words:
int a[] = new int[5];
a[4] = 5;
doesn't add anything. It just sets a value in memory.
So, if at all, we could say that we have somehow "O(1)" for accessing an address in memory, as nothing related to arrays depends on the number of entries.
Note: if you ask about ArrayList, things are different, as here adding to the end of the array can cause the creation of a new, larger (underlying) array, and moving of data.
An array is somewhere in memory. You don’t have control where, and you should not care where it is. The array is initialized when using the new type[size] syntax is used.
Accessing the array is done using the [] index operator. It will never modify size or order. Just the indexed location if you assign to it.
See also https://www.w3schools.com/java/java_arrays.asp
The time complexity is already correctly commented on. But that is the concern after getting the syntax right.
An old post regarding time complexity of collections can be found here.
Yes, it takes O(1) time. When you initialize an array, lets say, int[] foo = new int[10],
then it will create a new array with 0s. Since int has 4 bytes, which is 32 bits, every time assign a value to one element, i.e., foo[4] = 5, it will do foo[32 x input(which is 4)] = value(5); That's why array is 0-indexed, and how they assign values in O(1) time.

Accessing the value of a Java array position by index

I'm really new to Java and am just struggling with arrays a little bit. I've got a block of code that I've written when following a tutorial but am struggling to understand it and would love if someone could explain it to me.
I've tried working through it with various different methods (explaining to my duck, writing it down, etc.) and still can't get my head around it. I normally wouldn't ask and I always try desperately hard to work it out myself, but I just can't figure it out this time.
int[] values = new int[3];
values[0] = 10;
values[1] = 20;
values[3] = 30;
for(int i = 0; i < values.length; i++) {
System.out.println(values[i]);
}
I understand why:
The for loop iterates through the values in "values".
The loop keeps looping until i is less than the last value in the array.
But what I don't understand is why I need to write values[i] in the System.out.println() statement. What tells Java that i can be used in the array values[]?
Sorry if this is a trivial question for you but this is the best place I could think of to turn.
Java knows that values is an array type. Arrays in Java are indexed by integers, so here we have an integer called i. i goes from 0 to less than values.length (in this case is 3). So i will be 0, 1, and 2.
Indexing values with 0, 1, and 2 are equivalent to:
values[0]
values[1]
values[2]
Since JAVA is not a mind reader, unless you tell java value of which index you want to print JAVA will not be able to understand :)
So you have mention index like values[0] ,values[1] etc
values is the array name and 'i' is the index.
values[0] will print 10. values[1] will print 20.
Refer these links for more information:
http://www.homeandlearn.co.uk/java/java_arrays.html
http://www.javatpoint.com/array-in-java
Also learn how to debug the java code.
Let me try to explain in a simple way:
As soon as you use the statement:
int[] values = new int[3];
and assign values to it there will be three blocks of memory of integer size in memory.
as i is initialized to zero and each iteration in the for loop,
will execute the statement System.out.println(values[i]);
It will just substitute current value of i in values[i] that is values[0] for first round etc.
So it will check for already assigned values in the memory I talked about earlier and print it.
The System.out.println(values[i]); Tells the system to print the value at the given index in the array.
If we say System.out.println(values[0]);, the value at index 0 which is 10 is printed.
To print out all the values in the array, instead of typing the index for each value manually like values[1], values[2]. We use a for statement for(int i = 0; i < values.length; i++) creates a variable i and assigns it a value 0, so on the first run through the loop,values[i] is values[0].
After the first run through the loop, the i is incremented from 0 to 1 because of the i++ part of the for statement. on the second run values[i] is values[1] and what is printed is the value at index 1 which is 20. This continues as long as i < values.lenght; returns true.

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] = ...
}
}

Removing items from a multi dimensional array in Java

I am trying to remove items from a 3 dimensional array.
I understand that one of the best ways to do this is to convert the array to a list and whilst iterating through the original array remove those items from the list then convert the list back to an array and return it.
I tried this but got an type mismatch when coming back to the array. I suspect I have not done something with the dimensions when converting from array to list.
Advice?
import java.util.List;
import java.util.Arrays;
public class RepatitionRemoval {
public float[][][] process(float[][][] data) {
//this method with step through all of the the strokes and remove
//points which occupy the same position. This should help with time
//warping regconition
//Change the array to a list
List points = Arrays.asList(data);
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
for (int k = 0; k < data[i][j].length-1; k++) {
//if the current coordinate is the same as the one next
//then remove it
if (data[i][j][k] == data[i][j][k+1]) {
points.remove(data[i][j][k]);
}
}
}
}
float[][][] returnData = points.toArray();
return returnData;
}
}
First the following method doesn't do what you think it does:
//Change the array to a list
List points = Arrays.asList(data);
Btw a good IDE will automatically transform that for you to:
List<float[][]> points = Arrays.asList(data);
So when you next do a:
points.remove(data[i][j][k])
what happens is that data[i][j][k] primitive gets auto-boxed to the Float wrapper class and then the remove methods checks to see if it contains any element equal to your wrapped Float. It checks the entire list and doesn't find any Float because... You've got a list of float[][]. So basically your code will never remove any element from the list.
But anyway, you should know that should you find an element that would match in the remove method, you'd get an UnsupportedOperationException because Arrays.asList simply wraps your array and your "list" is still backed the float[][][] array. And you cannot resize arrays.
Then, anyway you typically cannot compare floating point numbers using ==:
if (data[i][j][k] == data[i][j][k+1]) {
for it is ususally a terrible way to check if two floating numbers are equal. Floating numbers should be compared using an epsilon (and you should always keep track of the error propagation).
Regarding your last line, you can cast back to a float[][][] but it's pointless because that list of float[][] you created in the first is backed by your original float[][][] and cannot be modified (well, you may modify individual elements, but you cannot resize it).
List points = Arrays.asList(data);
It's creating list (points) of two dimensional arrays not floats which is what you need.
But the way you are trying to achieve your requirement is not possible and logically invalid.
It sounds like you have to turn your array into list of list of list. Which will logically makes sense when you turn it back into a three dimensional array after removing elements because keeps track of the dimensions.
Is it not because you are trying to push back into a three dimensional array.
You would need to cycle through your array populating the dimensions 2 and 3, 1 by 1.
The whole idea seems overly complex because you would need to know the dimensions after removing the values, I think you are probably best maintaining the 3d array and removing values from that.
Multi-dimensional arrays are arrays of arrays. data is an array of float[][] objects; data[i] is an array of float[] objects, and data[i][j] is an array of float objects. Instead of converting data to a list, you need to convert data[i][j] to a list.
Also, you can't directly remove an item from the list returned by Arrays.asList(), as the list is directly backed by the array, which cannot be resized. Instead, you have to populate an ArrayList, remove the elements, then convert back to an array and replace the original (see this question)
Finally, you're working with an array of primitives (floats), you'll need to convert from float[] to ArrayList<Float> and back again. This isn't trivial; this question may help

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