Array copying confusion - java

int[] arr = {1, 2, 3, 4, 5};
int[] copy = arr;
copy[4] = 2;
System.out.println(arr[4]);
So it prints out 2 but I don't know why it would do that when arr doesn't equal copy. Shouldn't it still be 5 or am I dumb?

So it prints out 2 but I don't know why it would do that when arr
doesn't equal copy. Shouldn't it still be 5?
No, this is the expected behaviour. This is because copy and arr are referring to the same array object.
Create a copy in an immutable way as follows:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5 };
int[] copy = Arrays.copyOf(arr, arr.length);
copy[4] = 2;
System.out.println(arr[4]);
System.out.println(copy[4]);
int[] anotherCopy = arr.clone();
anotherCopy[4] = 2;
System.out.println(arr[4]);
System.out.println(anotherCopy[4]);
}
}
Output:
5
2
5
2

Instead of making a separate array, your compiler is just assigning a pointer to the the original array. In other words, both of the arrays are actually the same data underneath but with different names and pointers. A change to one will affect the other.

Related

Remove last occurrence of a specific integer from an array

For some reason, my solution is not complete. I got 80/100 from hidden spec tests.
What's wrong with my solution? There is probably a certain use case that I'm not thinking of.
How would space/time complexity change using an ArrayList instead of an array?
Is there a better way to tackle this problem?
My current solution handles:
an empty input array
negative/positive integer values in the input array
duplicates in the input array
sorted/unsorted input array
Instructions:
Write a Java method removeLastOccurrence(int x, int[] arr), which removes the last occurrence of a given integer element x from a given array of integer elements arr.
The method should return a new array containing all elements in the given array arr except for the last occurrence of element x. The remaining elements should appear in the same order in the input and the returned arrays.
The code on the right shows you a code framework in which the implementation of one static method is still missing. Provide this implementation and check that it is correct by either writing more tests yourself or using the provided tests and specification tests.
My code:
class RemoveLastOccurrenceArray {
/**
* Takes the array and the last occurring element x,
* shifting the rest of the elements left. I.e.
* [1, 4, 7, 9], with x=7 would result in:
* [1, 4, 9].
*
* #param x the entry to remove from the array
* #param arr to remove an entry from
* #return the updated array, without the last occurrence of x
*/
public static int[] removeLastOccurrence(int x, int[] arr) {
// if arr == null return null;
if (arr == null || arr.length == 0) return arr;
// return a new array which will be size arr.legnth-1
int[] res = new int[arr.length - 1];
// introduce an int tracker which keep tracks of the index of the last occurrence of x
int last_index = -1;
// traverse through the array to get the index of the last occurrence
for (int i = 0; i < arr.length; i++) if (arr[i] == x) last_index = i;
int i = 0, j = 0;
// copying elements of array from the old one to the new one except last_index
while (i < arr.length) {
if (i == last_index) {
if (i++ < res.length) {
res[j++] = arr[i++];
}
} else res[j++] = arr[i++];
}
// if we pass in x which is not in the array just return the original array
if (last_index == -1) return arr;
// are there duplicates in the array? - WORKS
// does the array have negative numbers? - WORKS
// Is the array sorted/unsorted - WORKS
return res;
}
}
Passing Unit Tests
import static org.junit.Assert.*;
import org.junit.*;
public class RemoveLastOccurrenceArrayTest {
#Test
public void testRemoveArray_Empty() {
int[] array = new int[0];
assertEquals(0, RemoveLastOccurrenceArray.removeLastOccurrence(5, array).length);
}
#Test
public void testFirstSimple() {
int[] input = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] result = {2, 3, 4, 5, 6, 7, 8, 9, 10};
assertArrayEquals(result, RemoveLastOccurrenceArray.removeLastOccurrence(1, input));
}
#Test
public void testLastSimple() {
int[] input = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] result = {1, 2, 3, 4, 5, 6, 7, 8, 9};
assertArrayEquals(result, RemoveLastOccurrenceArray.removeLastOccurrence(10, input));
}
#Test
public void testPositiveInMiddleDuplicate() {
int[] input = {1, 2, 3, 3, 4, 5};
int[] result = {1, 2, 3, 4, 5};
assertArrayEquals(result, RemoveLastOccurrenceArray.removeLastOccurrence(3, input));
}
#Test
public void testNegativeFirst() {
int[] input = {-3, -1, 2, -3, 3, 4, 5, 0};
int[] result = {-3, -1, 2, 3, 4, 5, 0};
assertArrayEquals(result, RemoveLastOccurrenceArray.removeLastOccurrence(-3, input));
}
#Test
public void testLasttoRemove() {
int[] input = {1, 4, 7, 9};
int[] result = {1, 4, 7};
assertArrayEquals(result, RemoveLastOccurrenceArray.removeLastOccurrence(9, input));
}
}
Why not try iterating backwards?
for(int i = arr.length; i => 0; i--)
{
if (arr[i] == x)
{
return ArrayUtils.remove(arr, i)
}
}
Then, after you find the index, you can use the Apache Commons ArrayUtils remove command to remove the item at the
This is the answer thank you very much!
Also, if there is no x to find, yours crashes ... mine doesn't. Maybe that's where the twenty marks went?
I was already checking for this but too late in my code. So I just had to move
if (last_index == -1) return arr; before the while loop, and I got 100/100 scores.
Would your prof prefer this? Just another way, and I don't think any more efficient than your answer. But maybe they like to see the java classes used ...
Does your prof not tell you where you lost marks? You can't improve if they don't tell you what they were expecting for full marks. But here was another way ... again, no better in my opinion, and not worth twenty more marks. I'll just post it, because it is 'another way.'
public int[] removeLastOccurrence2(int x, int[] arr) {
// if arr == null return null;
if (arr == null || arr.length == 0) return arr;
// Fill an ArrayList with your initial array ...
java.util.List list = new java.util.ArrayList(arr.length);
for (int i=0; i<arr.length; i++) {
list.add(arr[i]);
}
int[] res;
// Now ... use ArrayList methods to do the work.
// Also, if there is no x to find, yours crashes ... mine doesn't.
// Maybe that's where the twenty marks went?
if ( list.lastIndexOf(x) != -1 ) { // This screens for no x found at all ...
list.remove( list.lastIndexOf(x) ); // Done!
// Make a new array to return.
res = new int[list.size()];
for (int i=0; i<list.size(); i++) {
res[i] = (int) list.get(i);
}
} else {
// No 'x' found, so just return the original array.
res = arr;
}
return res;
}
How about reverse(), remove(), reverse()? Sorry if this is already mentioned in here somewhere and I missed it.

How to set an int array to another int array

How could I set an int[] array to another int[]?
Example:
int array[] = new int{1, 2, 3, 4, 5};
int array2[] = new int[]array;
or
int array[] = new int{1, 2, 3, 4, 5};
int array2[] = array[];
But it doesn't work!
Can somebody tell me how?
Why didn't you try with the most obvious:
int[] array2 = array;
You can try to use
array2 = Arrays.copyOf(array, array.length);
From the Java docs:
copyOf
Copies the specified array, truncating or padding with zeros (if
necessary) so the copy has the specified length. For all indices that
are valid in both the original array and the copy, the two arrays will
contain identical values. For any indices that are valid in the copy
but not the original, the copy will contain 0. Such indices will exist
if and only if the specified length is greater than that of the
original array.

Using a for loop to assign an array to another array

I have a project where by I used a sorting algorithm to sort an array but I am at the point where I now need to examine different arrays of different sizes and different values. Is there a way I can assign an array to a global array using a for loop
e.g
I have 12 arrays named array1 through to array12 and i need to assign them to a global array called array that is passed in to the sorting algorithm
The 12 arrays are passed in to the array from a file
Having variables that look like array1, array2, array3,..., array12 is a sure sign that you need a single array instead of all these variables. You should put these arrays into an array of arrays, and use array[x] to access them.
For example, instead of
int[] array1 = new int[] {1, 2, 3};
int[] array2 = new int[] {4, 5, 6};
...
int[] array12 = new int[] {34, 35, 36};
you would write
int[][] array = new int[][] {
new int[] {1, 2, 3},
new int[] {4, 5, 6},
...
new int[] {34, 35, 36}
};
Now instead of writing array5 you would write array[4] (4, not 5, because indexes of Java arrays are zero-based). This indexing can be done with a for loop:
int[][] array = new int[][] { ... };
for (int i = 0 ; i != array.length ; i++) {
callMySort(array[i]);
}
or from a foreach loop:
int[][] array = new int[][] { ... };
for (int[] sortMe : array) {
callMySort(sortMe);
}

Initializing an array inside of adding it to an Array List

Hi so pretty much what I have been trying to do is create a method that is passed an Array List of Integers and returns an ArrayList of int arrays. I want each array inside of the returned Array List to contain on of the values of passed Array List. here is what I have so far
public static ArrayList<int[]> createPossible(ArrayList<Integer> al)
{
ArrayList<int[]> returned = new ArrayList<int[]>();
for(int i = 0; i < al.size(); i++)
{
returned.add(new int [1]{al.get(i)});
}
return returned;
}
I think that you can see the basic point of what I'm getting at here. Just cant figure out how to properly initialize each new array inside of where I'm adding it to the returned ArrayList
Just use
new int[] {al.get(i)}
The length of the array is useless, since you pass a given number of values inside the curly braces.
This will work similar to what you have described but it uses List<Integer[]> rather than a List<int[]>. If you must have List<int[]> then it could be augmented to suit your needs.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class StackOverflow {
public static List<Integer[]> createPossible(List<Integer> al) {
List<Integer[]> returned = new ArrayList<Integer[]>();
for (int i = 0; i < al.size(); i++) {
returned.add(al.toArray(new Integer[0]));
}
return returned;
}
public static void main(String[] args) {
List<Integer> al = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 });
List<Integer[]> result = createPossible(al);
System.out.println(Arrays.deepToString(result.toArray()));
}
}
The output of the code above:
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]

Accessing Arrays via an identifier variable - JAVA

I am trying to access an array based on a number. Let me explain:
stringBuilder.append(array1[i]);
but I have 4 arrays, I would like to access the array like this:
int i;
int aNum;
stringBuilder.append(array(aNum)[i]);
so the array number selected depends on the value of aNum (1 - 4) where [i] being the location of the array (0 - n)
This code however doesn't work. Any ideas? Tried looking on google but can't find the correct code I need. It does seem simple but can't find the solution. Hope it makes sense!
You are referring to a two-dimensional array, which is an array of arrays. Here is an example:
/**
<P>{#code java TwoDArray}</P>
**/
public class TwoDArray {
public static final void main(String[] ignored) {
//Setup
int[][] intArrArr = new int[4][];
intArrArr[0] = new int[] {1, 2, 3, 4};
intArrArr[1] = new int[] {5, 6, 7, 8};
intArrArr[2] = new int[] {9, 10, 11, 12};
intArrArr[3] = new int[] {13, 14, 15, 16};
StringBuilder stringBuilder = new StringBuilder();
//Go
int indexOfIntInSelectedArray = 1; //The second element...
int indexOfArray = 2; //...in the third array.
stringBuilder.append(intArrArr[indexOfArray][indexOfIntInSelectedArray]);
//Output
System.out.println("stringBuilder.toString()=" + stringBuilder.toString());
}
}
Output:
[C:\java_code\]java TwoDArray
stringBuilder.toString()=10
Arrays can contain theoretically contain any number of dimensions:
https://www.google.com/search?q=multi+dimensional+array+java
https://www.google.com/search?q=three+dimensional+array+java
https://www.google.com/search?q=four+dimensional+array+java
Your array is a two dimensional array (array of arrays). You need to index using two pairs of brackets:
int rows = 4;
int cols = 5;
int[][] myArray = new int[rows][cols];
int row;
int col;
stringBuilder.append(myArray[row][col]);

Categories