I have two identical 2D array's of characters however I want to make it so that when I make changes to one it doesn't effect the other. I am assuming it is because they are sharing the same space in memory and was wondering how to stop this.
private char[][] a;
private char[][] b;
a = new char[8][];
b = new char[8][];
while(file.hasNext()) //reads 8 lines from a file and adds it to text to both arrays
{
char[] constant = file.nextLine().toCharArray();
a[i] = constant;
b[i] = constant;
i++;
}
then if i were to run the code
a[0][0] = 't';
then it also changes b[0][0] to 't'
Arrays are objects. When you assign them like this
int[][] firstArray = getArray(); // Get your array from somewhere
int[][] secondArray = firstArray; // Assign an array
you have only one array, but you have a second variable that references it. Essentially, secondArray[i][j] and firstArray[i][j] refer to the same object in memory by two different names.
To fix this, make a copy of the array. A simple way of doing it is to call the clone() method on the original array, like this:
int[][] secondArray = new int[firstArray.length][];
for (int i = 0 ; i != secondArray.length ; i++) {
secondArray[i] = (int[])firstArray[i].clone();
}
Note: clone() creates a shallow copy. If you
My first idea was:
char[] orig = // something;
char[] copy = orig.clone();
But be aware:
clone() only creates a shallow copy of an array. That means for a 2D-Array with chars you have to clone each subarray.
For further information about clone() click here.
Your code should look something like this
char[][] original = new char[3][3];
char[][] copy = new char[orignal.length][0];
for(int i = 0; i < original.length; i++){
copy[i] = original[i].clone();
}
I have two identical 2D array's of characters however I want to make it so that when I make changes to one it doesn't effect the other. I am assuming it is because they are sharing the same space in memory and was wondering how to stop this.
Arrays don't share memory. Nor do any other variables in Java.
Ergo if changes to one affect the other, you don't have two arrays at all. You only have one, with two references to it. Updating the array via one reference is visible via the other reference.
The solution is therefore to create two arrays, not just one.
Related
For an algorithm need a copy of a an array. Have an original and a temp. Need to process "turns" so can re use the temp, but need to start from that state.
After each turn, done with the temp (but need it again for next iteration). Is it better to copy the temp to the original or just assign the original to the temp and make a new array for the temp? Size will be 5x5 to 300x300 2D int array.
//int [][]orig //initialized elsewhere
int [][]newData = new int[orig.length][orig[0].length];
for (int i = 0; i < turns; i++) {
proc1Turn(orig, newData);
//after 1 turn copy newData to orig OR assign to orig
//and create new array for newData?
}
Which will be faster or another way? Will that be pretty much the same (for any system) if we have enough RAM/ free heap for the JVM?
Is it better to copy the temp to the original or just assign the original to the temp and make a new array for the temp?
It is better to do neither. Just swap the array references.
int [][] t = newdata;
newdata = orig;
orig = t;
This avoids allocating a new array (which needs to be cleared by the runtime, and which requires that the previous array be garbage collected at some point).
I need help in understanding how to initialize an object of a class in Java.
My code was something like this:
...
Test t[] = null;
...
for (i=0;i<20;i++)
t[i] = new Test(10,20);
...
When I write the above code in Eclipse, it gives me an error saying that "Null Pointer Access: The variable data can only be null at this location".
I tried all ways of correcting the error, but no luck.
You need to allocate space for the array itself, then initialize them elements.
Test[] t = new Test[20];
for (i = 0; i < 20; i++) {
t[i] = new Test(10, 20);
}
If the array's length is variable, you can just pass the value like you would any other variable.
int arraySize = 35;
Test[] t = new Test[arraySize];
for (i = 0; i < arraySize; i++) {
t[i] = new Test(10, 20);
}
Array size is fixed once you initialize it, but you can always get the array's length using the arr.length property.
You need to initialize your array by specifying its size.
Test[] t = new Test[20];
If you do not want to limit the array size. You may consider to use ArrayList, As elements are added to an ArrayList, its capacity grows automatically.
List<Test> testList = new ArrayList<Test>();
In Java an object array is immutable and must be initialized.
There are few things to do.
You can either provide the elements during the assignment:
Test t[] = { new Test(10, 20), new Test(30, 40) };
If you do not know the values, you can assign the array with proper allocation:
Test t[] = new Test[4];
In your situation you still need to initialize the array.
Generally speaking, this is not required at declaration, unless the variable is final.
Test t[]; // declaration
t[] = new Test[20]; // assignment
for ( i=0 ; i<20 ; i++ ) {
t[i] = new Test(10,20);
}
Java also has a group of classes that work with lists, arrays, key-value sets, and linked-lists.
If you need to use a mutable array, use the ArrayList object.
This will allow you to avoid the initialization.
Here is a brief example:
ArrayList<Test> t = new ArrayList<Test>();
for( i=0 ; i<20 ; i++ ) {
t.add(new Test(10,20));
}
Mutable lists are expensive in comparison to immutable object arrays, but the Java coders have really tweaked the ArrayList class, using the System.arraycopy() function.
So you will not see much of a performance degrade.
Simply put, only use a mutable ArrayList when you have absolutely no way of knowing your required allocation space.
Need to initialize your array test[] like below and then use it
Test[] t = new Test[20];
In java, datatypes can be primitive or reference. Reference types are either Class or Interface type or Array type.
When you want to create an Array of objects, first you need to declare and instantiate the array Object itself and then instantiate the required objects of the class and assign them to the array object.
ArrayDataType[] ArrayName=new ArrayDataType[Dimensions];
for(int i=0;i<Dimensions;i++){
Arrayname[i]=new ObjectDataType();
\\ where the ObjectDatatype can be either ArrayDataType or SubType
}
Try
Test[] t = new Test[20];
When you set t to null it tries to access an array that isn't there.
How would I copy an array say
float arraytobecopied[] = {1.20,2.50,3.60};
to another array that has data in it already say
float newarray[] = {5.20,6.30,4.20};
I want to add the the arraytobecopied to the end of the new array and keep the values in the array. also as a side note this would be an on going process adding to the end of the array every time.
Should i just use a for loop? or is there a better way.
(Can't use Array) already tried:(
This question has been asked here before, You can see this page for the answer. How can I concatenate two arrays in Java?
Use System.arraycopy
public static void arraycopy(Object src,
int srcPos,
Object dest,
int destPos,
int length)
You can't increase the size of the original array. But you could create a new array, copy both source arrays into it, and assign your reference variable to it.
For example, here's a sketch of a simple implementation. (An alternative is to use System.arraycopy().)
float[] newerArray = new float[ newarray.length + arraytobecopied.length ];
for ( int i = 0; i < newarray.length; ++i ) {
newerArray[i] = newarray[i];
}
for ( int i = 0; i < arraytobecopied.length; ++i ) {
newerArray[ newarray.length + i ] = arraytobecopied[i];
}
newarray = newerArray; // Point the reference at the new array
Alternatively, you could use a java.util.ArrayList, which automatically handles growing the internal array. Its toArray() methods make it easy to convert the list to an array when required.
The easiest approach from a programming perspective is to use a List<Float> (if you can use Float values instead of float) or a third-party library such as Apache Commons Collections or Trove that provides dynamic arrays of primitives.
If you need to use a simple array of primitives (and not a wrapper class), you can use a couple of methods in the java.util.Arrays and java.lang.System classes to help:
int len1 = newarray.length;
int len2 = arraytobecopied.length;
float[] result = Arrays.copyOf(newarray, len1 + len2);
System.arraycopy(arraytobecopied, 0, result, len1, len2);
// result now contains the concatenation of newarray and arraytobecopied
Note that you cannot change the length of an array object; you can only reassign the variable to a new array (e.g., newarray = result;).
The easiest can be:
List<Float> floats = new ArrayList(arraytobecopied);
floats.addAll(newarray);
arraytobecopied = floats.toArray(new float[0]);
If you dont want to use anything from java.Util at all.
How about writing one method that updates the destination array with src array. Now when u copy elements make sure that the size is enough in destination array. Otherwise when you create a new array, create it with double size and copy the elements, this may help in avoiding a new array creation everytime and doing iterations to populate the complete array again after resizing.
Somewhat similar to how array list maintains size of array inside it.
I have defined an int[][] object. Because it is an object, if i send it to a method as a parameter, it will only send it's reference, so any changes to the array in the method, will influence it in the main program. So i would like to make a clone of this object inside the method, but i'm not sure how to accomplish this.
I was thinking of something like so:
private void myMethod( int[][] array )
{
//Define our temporary array (clone)
int[][] newArray = new int[3][3];
//Go through the elements of the array
for .... row = 0; row < ..; row++
for ..... col = 0; col < ..; col++
//Copy individual elements from one array to another
newArray[row][col] = array[row][col];
}
but will the above code copy each element from array into newArray as value (so... a clone of the item), or just the reference?
If so, how can this be accomplished. If i were to use ArrayLists instead of int[][] objects, there is the clone() method or something like that, but i haven't got that method for int[][] objects :(
Also, if i'm not mistaken if i do this inside the method newArray = array , that will copy just the reference again, so both will point to the same int[][] object :(
P.S. I know i could just test this, but i'd like to discuss it with you guys a bit, and see what's what exactly.
but will the above code copy each element from array into newArray as value (so... a clone of the item), or just the reference?
You're copying each element of the array, and each element is an int, so you're fine. The new array will be completely independent of the original.
Note that if instead you'd done:
int[][] newArray = new int[3][];
for (int i = 0; i < 3; i++) {
newArray[i] = array[i];
}
... then that would just have copied references to the three existing int[] arrays into newArray. But you've allocated a completely new set of arrays (one int[][] and 3x int[]) so it's all independent.
You could use clone() on the matrix and on each array corresponding to a row in the matrix, it will work without problems because you're cloning a matrix of primitive values, like this:
int[][] matrix = new int[3][3];
// ... matrix gets filled ...
int[][] copy = matrix.clone();
for (int i = 0; i < matrix.length; i++)
copy[i] = matrix[i].clone();
The above will create a copy matrix which is independent of matrix, meaning that you can change the values of the copy without affecting the original.
Primitive types, such as int, are not reference types. Thus, going through all the items and copying them one by one will make a copy-by-value.
In short, your code is correct.
int is a primitive type, you always pass them around as value, not as reference, so you code will indeed create a new copy of the array.
You might want to consider using Arrays.copyOf(), it may be faster.
I have an array for example:
String [][] test = {{"a","1"},
{"b","1"},
{"c","1"}};
Can anyone tell me how to remove an element from the array. For example I want to remove item "b", so that the array looks like:
{{"a","1"},
{"c","1"}}
I can't find a way of doing it. What I have found here so far is not working for me :(
You cannot remove an element from an array. The size of a Java array is determined when the array is allocated, and cannot be changed. The best you can do is:
Assign null to the array at the relevant position; e.g.
test[1] = null;
This leaves you with the problem of dealing with the "holes" in the array where the null values are. (In some cases this is not a problem ... but in most cases it is.)
Create a new array with the element removed; e.g.
String[][] tmp = new String[test.length - 1][];
int j = 0;
for (int i = 0; i < test.length; i++) {
if (i != indexOfItemToRemove) {
tmp[j++] = test[i];
}
}
test = tmp;
The Apache Commons ArrayUtils class has some static methods that will do this more neatly (e.g. Object[] ArrayUtils.remove(Object[], int), but the fact remains that this approach creates a new array object.
A better approach would be to use a suitable Collection type. For instance, the ArrayList type has a method that allows you to remove the element at a given position.
There is no built-in way to "remove" items from a regular Java array.
What you want to use is an ArrayList.
You could set the entry in the array to null (test[0][1] = null;). However, "removing" the item such that the array will have one element less than before is not doable without recreating the array. If you plan to change data in the data structure regularly an ArrayList (or another Collection class depending on your needs) might be more convenient.
My solution is:
You cannot remove an element from an array => it's correct, but we can do something to change current array.
No need assign null to the array at the relevant position; e.g.
test[1] = null;
Create a new array with the element removed; e.g.
String[][] temp = new String[test.length - 1][];
Need to get index at string/array to remove: IndexToRemove
for (int i = 0; i < test.length-1; i++) {
if (i<IndexToRemove){
temp[i]=test[i];
}else if (i==IndexToRemove){
temp[i]=test[i+1];
}else {
temp[i]=test[i+1];
}
}
test = temp;
Hope it helpful!