Last active
December 20, 2015 01:59
-
-
Save CarloMicieli/6053423 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ReferenceSamples { | |
public static void main(String[] args) { | |
references(); | |
equality(); | |
} | |
private static void equality() { | |
Integer i1 = 1; | |
int i2 = i1; | |
assert i1 == i2 && i1.equals(i2); | |
//assert i2.equals(i1); "error: int cannot be dereferenced" | |
float f1 = 1.0f; | |
Float f2 = f1; | |
assert i1 == f1 && !i1.equals(f1); | |
// assert i1 == f2; "error: incomparable types: Integer and Float" | |
assert !i1.equals(f2); | |
assert i1.intValue() == f2 && i1 == f2.intValue(); | |
} | |
private static void references() { | |
TestClass t = new TestClass(); | |
String[] a = {"one", "two", "three"}; | |
t.arrays(a); | |
assert a[0] == "aaa"; | |
assert a[1] == "aaa"; | |
assert a[2] == "aaa"; | |
// reference final method are mutable! | |
Holder h1 = new Holder(42); | |
t.add(h1, 10); | |
assert h1.getI() == 52; | |
// strings are immutable, any value change creates a new reference | |
String s1 = new String("1"); | |
String s2 = s1; | |
assert s1 == s2 && s1.equals(s2); | |
s1 = new String("1"); | |
assert s1 != s2 && s1.equals(s2); | |
// stringbuilder is immutable too | |
StringBuilder sb1 = new StringBuilder("Hello"); | |
StringBuilder sb2 = sb1; | |
assert sb1 == sb2 && sb1.toString().equals(sb2.toString()); //equals is not overriden | |
sb2.append(" world"); // yep, that's silly | |
assert sb1 == sb2 && sb1.toString().equals(sb2.toString()); | |
// different with mutable objects | |
Holder h2 = new Holder(1); | |
Holder h3 = h2; | |
assert h2 == h3 && h2.getI() == h3.getI(); | |
h3.setI(5); | |
assert h2 == h3 && h2.getI() == h3.getI(); | |
h2 = new Holder(5); | |
assert h2 != h3 && h2.getI() == h3.getI(); | |
} | |
} | |
class TestClass { | |
void add(final Holder h, int i) { | |
int n = h.getI(); | |
h.setI(n + i); | |
// compile error > h = new Holder(999); | |
} | |
void arrays(String[] array) { | |
int i = 0; | |
for (String s : array) { | |
array[i++] = "aaa"; | |
} | |
} | |
} | |
class Holder { | |
private int i; | |
public Holder(int i) { | |
this.i = i; | |
} | |
public void setI(int i) {this.i = i;} | |
public int getI() {return i;} | |
public String toString() { return "Hold: " + i; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment