Java - Old array always is equal to new array? - java

I'm not very good at programming but right now, I need to do program a little Java application and I'm running into a weird problem. I've been trying to solve this for hours now.
Here's the problem:
I'm saving a small amount of my screen (20x20) to my program. I do this by looping through every pixel, saving it's RGB into an array via Java.awt.robot. With the following function, the program should save the copied image to 3 arrays (R, G and B) before getting the new area of the screen (I want to compare them later and look for changes). The one damn thing: The old arrays in which I save the data before overwriting the main arrays are always overwriting without me telling them to.
private void fillArrayData(){
oldDataR = dataR; <----- The problem is here. These arrays are now overwritten with the
oldDataG = dataG; <----- current data, just before I write stuff to dataR, G and B.
oldDataB = dataB; <----- As you see, I don't modify oldDataR, G, B later on.
scanArea.x = MouseInfo.getPointerInfo().getLocation().x;
scanArea.y = MouseInfo.getPointerInfo().getLocation().y;
for(int i = 0; i<scanSize; i++){
for(int n = 0; n<scanSize; n++){
dataR[i][n] = (rbt.getPixelColor(scanArea.x+i, scanArea.y+n)).getRed();
dataG[i][n] = (rbt.getPixelColor(scanArea.x+i, scanArea.y+n)).getGreen();
dataB[i][n] = (rbt.getPixelColor(scanArea.x+i, scanArea.y+n)).getBlue();
}
}
}
Even though I never access oldDataR, oldDataG and oldDataB later on, it everytime is equal to the dataR, dataG and dataB after this void finishes. That doesn't make sense as I'm writing new data to the three main arrays (dataR, dataG, dataB) AFTER I saved them to the oldData-Arrays. And yes, I made sure that the data which is received by rbt.getPixelColor is not the same as before.
Please help me, I'm really frustrated by now but need to keep going.

That is happening because oldDataR (and the rest) is just another variable pointing to the same array, if you want to keep the old values in the array separately, and modify the original one, you need to copy it.
This post can be helpful for copying two-dimensional arrays:
copy a 2d array in java

You are passing your arrays as references, so, in the end it is the same array in the pointers of the two variables.
Have you tried array copy?
System.arraycopy()
or
Arrays.copyOf()
Your code would look like:
oldDataR = Arrays.copyOf(dataR);
Edit
I missed the multi dimension of the arrays, just follow #khachik link suggestion so you can handle the two dimensions.

Related

Java ArrayList of Type Class behaves like it only has objects with reference to a global object

I need some help here - I want to do a little card game for learning reasons.
I have a class (Tree/Baum) and an ArrayList "TreeList" of several trees of object Tree.
Now I want to load different random objects of that class in a new ArraList called "PlayersHand".
To do this I have created a for-loop with a tmpObj of type Tree which loads a random index from ArrayList"TreeList" of all Trees. After that it modifies some values of the tmpObj by random (f.e. tree height). Then it adds this whole tmpObject to the ArrayList "PlayersHand".
The Problem is, that when I read out the values of the objects inside PlayersHand the modified values don't show the right way. They always show the last value of the treetype, so f.e. if the last tree of type ACER was 20m high, all the previous trees of type ACER are 20m high too.
It seems like all the objects in the ArrayList "playersHand" are just pointers to the different objects of ArrayList "TreeList".
But why ? And how can I fix it?
The code where the objects are copied:
//"PlayersHand get cards
for(int i=0;i<amountOfCards;i++)
{
int randomNr = (int)(Math.random()* TreeList.size());
Tree tmpTree = TreeList.get(randomNr);
tmpTree.modifyValues();
playersHand.add(tmpTree);
for(int y=0; y<playersHand.size();y++)
{
Tree tmpTree2 = playersHand.get(y);
System.out.println(" - different values of that object shown here - ");
}
}
Edit: Previously I had a more complex scenario. I tried to reduce complexity for better understanding.
I solved it - If someone has the same issue :
You have to use a copy constructor.

Java - A loop in a loop and the format gets lost

I'm French so excuse my English not necessarily correct.
I explain the context, I currently have a String array list named "tempCustomerDrugsIdsList" (var1) and another string array list named "tempDrugsTableList"(var2).
When I make a loop "For" on "var1" then another one in "var2","var2" loses its format, i. e. upper case is replaced by lower case and spaces are deleted.
I tested with another loop with the same type of variables (but empty), the result being the same I think the problem comes from my way of using java. Being on vb. net before, I must have taken some bad habits !
I don't know how to solve this problem, I've only been working in java for 2 weeks.
Thank you for helping me.
[EDIT]
My problem was:
List<String[]> tempDrugsTableList = otherList;
But this code doesn't duplicate the list.
AxelH gave me the following solution:
List<String[]> tempDrugsTableList = new ArrayList<String[]>(otherList);
Well, you are not doing a "copy" of the list
tempDrugsTableListCopy = tempDrugsTableList; // Get copy of original tempDrugsTableList for comparate
but sharing the reference, every update done in the tempDrugsTableListCopy will be done in the original list (same reference, same adress in memory). Since you are updating that copy in the following loops ... you update the original list too. What you want is to clone the list.
You could do it simply with copyList = new ArrayList(originalList); or for a deep clone, you need to iterate each element to duplicate those. (array need to be duplicated too if you change the value in those)
"String[]" tmpCustomerIds means you are getting a string array from a string array, which you would be using in a 2d array. Try it with just "String" in the for each loops. I am assuming you are using 1d arrays in this case.

Writing an expanding array

I have a piece of code that waits for data to come from a shaky network. The machine that runs the code could also go down at any moment.
So I am writing in-coming data to the disk as the program runs. If the system goes down, I would have data up to that point. I can save each data object in a separate JSON file but that would end up with hundreds of thousands of files.
What I would like to do is to append to one JSON file that can be read back as an array or list. Each time the data comes in it is written to the end without re-writing the older data. What is the best way to do that?
You can create a FileWriter, with true as the second constructor argument. This makes a FileWriter that will append to an existing file, instead of replacing it (see http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html).
The method does not change the value of OrigArray; all it does is store a clone of a clone in it, so in effect the value isn't changed.
I think what you want is this:
public void expand() {
String[] newArray = new String[OrigArray.length + 1];
System.arraycopy(OrigArray, 0, newArray, 0, OrigArray.length);
//an alternative to using System.arraycopy would be a for-loop:
// for(int i = 0; i < OrigArray.length; i++)
// newArray[i] = OrigArray[i];
OrigArray = newArray;
}
This creates an array that has a size 1 greater than OrigArray, copies the content of OrigArray into it and assigns that array to OrrigArray. Unless you want to remember how many times expand() has been called, there shouldn't be a reason to have the variable size.

How to write an array of x coordinates and an array of y coordinates?

I need to make these arrays because I am trying to make a mouse glide from the first point to the second, the second to the third, and etc... Each glide should be broken into 25 steps and take 1000 milliseconds.
I don't know how to start the method exactly.
public void glide(int [] x, int [] y)
I even have doubt that i set this method correctly.
I really don't have a clue how to start this method.
The better approach would be to use a multi-dimensional array in order to store your values. Here is an example:
public void glide(int[][] points)
{
// ...
}
int[][] p = new int[25][25];
// assign points
glide(p);
Well that method takes two arrays as parameters. So to use the glide method you should already have two arrays written. In Java you make the array by saying:
private int[] x-coords = new int[SIZE] // SIZE is how many elements will be in the array
private in[] y-coords = new int[SIZE] // They should be the same if you're using them as coordinates
then to USE the glide method you would say
glide(x-coords,y-coords);
Now as far as writing that method goes.... it's going to depend on alot of things and if you showed more of the code then that would help alot. In essence what you want to do is:
public void glide(int[] x, int[] y) {
// Standard loop to iterate through all the elements of the x array
for(int i=0; i<x.length; i++) {
// This moves the pointer
mouseMove(x[i],y[i]);
// This pauses
try {
Thread.sleep(1000);
} catch(InterruptedException e) {}
}
}
Now what this is all doing is moving the mouse (hopefully in small increments) every 1000 milliseconds. The way you're breaking up the coordinates isn't the most effecient way (why use arrays instead of using math in the code) but it will work that way. Just requires alot more math on your part instead of the computers. Basically you're wanting to glide from the coorderinates (x[0],y[0]) to (x[24],y[24]). So the starting point is going to be the first points in the arrays and the end point is the last points in the arrays. Then every number in between should move by however much it needs to move.
The way that was presented in How to move a mouse smoothly throughout the screen by using java? is going to be the most efficient way. All he did was let the computer do the math and instead of using arrays he just put in a starting point and an ending point. You should read over that and try to understand that code as well as possible.

How do I remove objects from an Array in java based on certain condition?

:)
I have
int[] code = new int[10];
It has the following values:
code[0] = 1234;
code[1] = 2222;
code[2] = 2121;
code[3] = 4321;
code[4] = 3333;
code[5] = 2356;
The code in this case refers to the serial number of the files.
The user is suppose to enter the code of the file to remove that specific file.
Let's say user enter 3333 as the code to remove.
code[4] = 3333 would be removed and code[5] = 2356 will move up to take its place. See below...
code[0] = 1234;
code[1] = 2222;
code[2] = 2121;
code[3] = 4321;
code[4] = 2356;
How would I tackle this problem?
I read up that using an Array List would make my life much easier.
However, I was told to just use an array.
Any help please? :)
How would I tackle this problem?
Allocate a new array and copy all of the values that you want to keep from the existing array to the new one.
You could also update the array in place, filling the "hole" at the end of the array with some special value that can't be a legal code.
Since this is a "sounds like homework" question, I'll leave you to figure out how to code it. (It is pretty simple. Just a loop, a test, and some careful manipulation of a second index.)
That's simply not possible. Arrays have a fixed size, so you'll have to make a second array with its size reduced by 1 and copy all values except the one you want to keep. Or keep track of the "working size" of the array separately, at which point you're begun to reimplement ArrayList.
You can simply set the value to something which is improbable (like -1 to save yourself the trouble of moving around and adjust arrays using System.arrayCopy or the likes. This of course assumes that the aim is to get the functionality working. If "moving" elements is an absolute requirement, you'd have to create a new array as mentioned by another comment here.

Categories