I was wondering how something like this would work.
int[] a = {5, 3, 4};
int[] b = {3, 4, 5};
a = b;
Does this mean that a will now reference b.
So if I do a[0] it will be 3?
Also if this is the case what happens to the items in the old array?
Does this mean that a will now reference b. So if I do a[0] it will be 3?
Sort of. a doesn't reference b (the variable), it references the same array that b refers to. There's no connection between a and b, it's just that they both refer to the same array (after the a = b assignment).
Also if this is the case what happens to the items in the old array?
The old array is eligible for garbage collection, since nothing refers to it anymore. Since it's an array of primitive values, the items are part of the array, so GC'ing the array inherently means the items are GC'd.
In memory, initially you had:
+−−−−−−−−−+
a:Ref33423−−−>| (Array) |
+−−−−−−−−−+
| 5 |
| 3 |
| 4 |
+−−−−−−−−−+
+−−−−−−−−−+
b:Ref54687−−−>| (Array) |
+−−−−−−−−−+
| 3 |
| 4 |
| 5 |
+−−−−−−−−−+
Then after the a = b;, you have:
+−−−−−−−−−+
| (Array) |
+−−−−−−−−−+
| 5 |
| 3 |
| 4 |
+−−−−−−−−−+
a:Ref54687−−+
|
| +−−−−−−−−−+
+−>| (Array) |
| +−−−−−−−−−+
| | 3 |
b:Ref54687−−+ | 4 |
| 5 |
+−−−−−−−−−+
...and eventually GC will remove that orphaned array:
a:Ref54687−−+
|
| +−−−−−−−−−+
+−>| (Array) |
| +−−−−−−−−−+
| | 3 |
b:Ref54687−−+ | 4 |
| 5 |
+−−−−−−−−−+
I should note that if it had been an array of objects, the array and each object the array referred to would potentially have different lifespans, GC'ing the array doesn't necessarily mean the objects in it are GC'd (it depends on whether anything else has references to them).
Does this mean that a will now reference b. So if I do a[0] it will be 3?
Yes, you can think a and b as remote controllers of two TVs. a=b means a is pointing where b is pointing. So a[0] will be 3.
Also if this is the case what happens to the items in the old array?
As there are currently no references to the first array, they're are going to be garbage collected.
Yes, now a will refer b and a[0] will be 3.
Also, now there will be no reference to the old array so it will be eligible for Garbage Collection.
int[] a = {5, 3, 4};
int[] b = {3, 4, 5};
System.out.println(a[0]);//5
a=b;
System.out.println(a[0]);//3
Related
I am trying to solve this Recursive Exercise:
In a multidimensional board (M x N), which everyone of his elements can be empty or full.
"stain" size is the number of elements who are next to each other and has the value 'x'.
for example this is a multidimensional array (the numbers are the row/column number)
| 0 | 1 | 2 | 3 | 4 |
0 | | x | | | x |
1 | x | | | x | x |
2 | | | x | x | |
3 | x | | | | |
4 | x | x | x | | |
There are 3 stains:
Rows (0,1), (1,0) - Size of 2
Rows (0 ,4) ,(1 ,3) ,(1 ,4) ,(2 ,2) ,(2 ,3) - Size 5
Rows (3 ,0) ,(4 ,0) ,(4 ,1) ,(4 ,2) - Size 4
We need to write a recursive method who has a signature of:
public static int stain (char [][] mat, int row, int col)
the method will get a row and a column and calculate the stain size from that place, if there is no stain it will return 0.
I tried to write the method to solve it but looks like I was doing it kinda messy... can you direct me to the right direction? I'm not looking for a straight answer.
Thanks.
I can't do loops!
I'm trying to refresh my skills in recursion and so far everything has gone well. However, I have never seen a problem where a string is the value of two recursive calls. Does the first recursive call ignore the rest of the statement? Is the 2nd recursive call still taken into account when it is resolved? I tried tracing it under the assumption that like a return statement, the first recursive call would break the loop. Therefore, I was under the impression that the rest of the code in the if statement would not be taken into account.
public class Example {
public static String encrypt(String word) {
int pos = word.length() / 2;
if (pos >= 1)
word = encrypt(word.substring(pos)) + encrypt(word.substring(0,pos));
return word;
}
public static void main(String []args){
System.out.println(encrypt("SECRET"));
}
}
While my expected output was "TETRET", the actual output was supposed to be "TERCES." Anyone mind explaining where my tracing or logic went wrong?
I tried tracing it under the assumption that like a return statement, the first recursive call would break the loop.
This is incorrect. Both will be evaluated.
word = encrypt(word.substring(pos)) + encrypt(word.substring(0,pos));
The first recursive call will get pushed onto the stack, and the second will be saved on the stack to be evaluated once the first call has been returned to the call stack. Here's a visual representation:
1
/ \
2 5
/ \
3 4
This is assuming 3, 4, and 5 reach the base case and thus do not continue the recursion
The word is returned in reverse order. I am unsure what you were trying to do instead. Here is a partial trace of your code, using "ABCDEF" instead of "SECRET", showing how it works :
+=================================+====================+===========================================+==============+==========================================+==============+
| word (initial call) | pos (initial call) | word (call 2) | pos (call 2) | word (call 3) | pos (call 3) |
+=================================+====================+===========================================+==============+==========================================+==============+
| "ABCDEF" | 3 | | | | |
+---------------------------------+--------------------+-------------------------------------------+--------------+------------------------------------------+--------------+
| encrypt("DEF") + encrypt("ABC") | | "DEF" | 1 | | |
+---------------------------------+--------------------+-------------------------------------------+--------------+------------------------------------------+--------------+
| | | encrypt("EF") + encrypt ("D") | | "EF" | 1 |
+---------------------------------+--------------------+-------------------------------------------+--------------+------------------------------------------+--------------+
| | | | | encrypt("F") + encrypt("E") | |
+---------------------------------+--------------------+-------------------------------------------+--------------+------------------------------------------+--------------+
| | | | | (call 4 returns "F", call 5 returns "E") | |
+---------------------------------+--------------------+-------------------------------------------+--------------+------------------------------------------+--------------+
| | | | | "FE" | |
+---------------------------------+--------------------+-------------------------------------------+--------------+------------------------------------------+--------------+
| | | (call 3 returns "FE", call 6 returns "D") | | | |
+---------------------------------+--------------------+-------------------------------------------+--------------+------------------------------------------+--------------+
| | | "FED" | | | |
+---------------------------------+--------------------+-------------------------------------------+--------------+------------------------------------------+--------------+
Here is the order in which the calls are made and "resolved" (by resolved, I mean that the return statement of the function is executed) :
encrypt("ABCDEF")
encrypt("DEF")
encrypt("EF")
encrypt("F")
resolution of encrypt("F") // returns "F"
encrypt("E")
resolution of encrypt("E") // returns "E"
resolution of encrypt("EF") // returns "FE"
encrypt("D")
resolution of encrypt("D") // returns "D"
resolution of encrypt("DEF") // returns "FED"
encrypt("ABC")
(...)
Of course the same logic applies to encrypt "ABC" as it did to encrypt "DEF", so if you understand this part you should understand the rest.
If you place the print statement as I have shown, you can see how the returned word and pos are altered. Then just backtracking off the stack, the word is reconstructed in reverse order.
public class Example {
public static String encrypt(String word) {
int pos = word.length() / 2;
System.out.println(word + " " + pos);
if (pos >= 1) {
word = encrypt(word.substring(pos)) + encrypt(word.substring(0, pos));
}
return word;
}
public static void main(String[] args) {
System.out.println(encrypt("SECRET"));
}
}
Produces the following output:
SECRET 3
RET 1
ET 1
T 0
E 0
R 0
SEC 1
EC 1
C 0
E 0
S 0
TERCES
i wrote a function to change an input matrix and return the changed matrix in java.
but when i want use input matrix after calling this function, i see that my input matrix has been changed.
My Up Function:
char[][] up(char[][] state, int[] empty){
int ie = empty[0];
int je = empty[1];
if(tools.checkMoves(state,1,ie,je)){
state[ie][je] = state[ie-1][je];
state[ie-1][je] = '0';
}else{
System.out.println("Move not allowed");
}
return state;
}
print matrix then call function and again print matrix
System.out.println(gameGenerator.printGame(nextState));
System.out.println(gameGenerator.printGame(moves.up(nextState,tools.getEmpty(nextState))));
System.out.println(gameGenerator.printGame(nextState));
Answer is:
1.print input matrix
-------------
| 1 | 2 | 3 |
| 5 | 7 | 6 |
| 4 | | 8 |
-------------
2.print matrix returned from function
-------------
| 1 | 2 | 3 |
| 5 | | 6 |
| 4 | 7 | 8 |
-------------
3.print input matrix after calling up function and it's CHANGED!
-------------
| 1 | 2 | 3 |
| 5 | | 6 |
| 4 | 7 | 8 |
-------------
please help ! Thanks all
You are modifying your input matrix in those two lines:
state[ie][je] = state[ie-1][je];
state[ie-1][je] = '0';
Java is an object-oriented language. When you pass an object to a method, you pass its reference. The reference is copied but not the object itself. When you modify the object inside the method, it is still modified after the method (which is normal since it is the same object).
If you don't want your method to create any side effect, you have create a copy of the matrix at the beginning of your method and modify the copy.
Additional note:
You may wonder why when the input is a primitive type, then the value is still the same outside the method, like this:
public void modify(int i){
i = 5;
}
That's because Java is pass by value, which means that the value of i is copied when the method is called, so only the copy is modified. As I wrote above, objects references are also passed by value, which means that the reference is copied. (to explain it roughly, you copy the value of the pointer to the object).
If you'd like a more detailed explanation, you can read this : http://www.javadude.com/articles/passbyvalue.htm
This question already has answers here:
Assigning in Java?
(5 answers)
Closed 4 years ago.
ArrayList<Integer> aList1=new ArrayList<Integer>();
ArrayList<Integer> aList2=new ArrayList<Integer>();
aList1.add(1);
aList2=aList1;
aList1.clear();
System.out.println(aList1.size());
System.out.println(aList2.size());
Why here both lists have size zero? As per my understanding aList1.size() should be 0 and aList2.size() should be 1.
When you make an assign like this :
aList2 = aList1;
The aList2 will point to the same Memory address of aList1 for that when you change aList1 the first also changed.
Consider you have a list like this :
+---+ +---+
O---> | 1 | --- | 2 |
+---+ +---+
When you assign :
aList2 = aList1;
It will be like this :
+---+ +---+
+--> L1---> | 1 | --- | 2 |
| +---+ +---+
|
L2--+
When you change L1 the
aList1.clear();
the other list also will be affected
+--> L1---> null
|
|
L2--+
to solve this issue you can use :
aList2 = new ArrayList<>(aList1);
This will return :
0
1
I'm trying to implement a minesweeper solver using a SAT solver (sat4j) and I have a simple understanding of how they work. But one thing I can't figure out is how to represent the x+y+Z+....=2 for mines, since SAT solvers use Boolean input. Something such as in the table below:
| a | b | c | d | e |
| f | 2 | g | 3 | h |
| i | j | k | l | m |
You could write a+b+c+f+g+i+j+k = 2 and c+d+e+g+h+k+l+m= 3.
if by a+b+c+f+g+i+j+k = 2 you mean that the surrounding cells contain exactly two mines, then your letters really are Boolean variables, and that constraint is called a cardinality constraint.
This is supported out of the box by Sat4j.
You may find some hints here:
https://sat4j.gitbooks.io/case-studies/content/