🔖
Java | "プリミティブ型" , "参照型" , "文字列リテラル" | シャローコピー | ディープコピー
Java
シャローコピー(shallow copy), ディープコピー(deep copy)
種類 | 内容 |
---|---|
shallow copy | シャローコピーは、データの一部分だけをコピーすることで、元のデータとコピーしたデータが同じ場所を参照しているイメージ。 |
deep copy | ディープコピーは、元のデータに似たデータの新しいバージョンを作成することで、別々の場所に保存される。 |
"プリミティブ型" , "参照型" , "文字列リテラル"
- "文字列リテラル"はプリミティブ型ではなく、暗黙のうちに生成されたString型インスタンスへの"参照"である。
import java.util.*;
public class Main {
public static void main(String[] args){
String literal01 = "string";
String literal02 = "ing";
/* 同じ文字列で同じ参照のため、trueと判定される */
System.out.println(literal01 == "string");
/* コンパイル時の時点で"string"となるためtrue判定される */
System.out.println(literal01 == ("str"+"ing"));
/* 文字列結合によって新しいオブジェクトへの参照となってしまうために、false判定される */
System.out.println(literal01 == ("str" + literal02));
}
}
true
true
false
Example 4.3.1-2. Primitive and Reference Identity
import java.util.*;
class Value { int val; }
class Main {
public static void main(String[] args) throws Exception{
int i1 = 3;
int i2 = i1;
i2 = 4;
System.out.print("i1==" + i1);
System.out.println(" but i2==" + i2);
Value v1 = new Value();
v1.val = 5;
Value v2 = v1;
v2.val = 6;
System.out.print("v1.val==" + v1.val);
System.out.println(" and v2.val==" + v2.val);
}
}
/* Example 3.10.5-1. String Literals */
/* https://docs.oracle.com/javase/specs/jls/se11/html/jls-3.html#jls-3.10.5 */
import java.util.*;
class Main {
public static void main(String[] args) throws Exception {
String hello = "Hello", lo = "lo";
System.out.println(hello == "Hello");
System.out.println(Other.hello == hello);
//System.out.println(other.Other.hello == hello);
System.out.println(hello == ("Hel"+"lo"));
System.out.println(hello == ("Hel"+lo));
System.out.println(hello == ("Hel"+lo).intern());
}
}
class Other { static String hello = "Hello"; }
true
true
true
false
true
12.5. Creation of New Class Instances
/* Example 12.5-1. Evaluation of Instance Creation */
/* https://docs.oracle.com/javase/specs/jls/se11/html/jls-12.html#jls-12.5 */
import java.util.*;
class Point {
int x, y;
Point() { x = 1; y = 1; }
}
class ColoredPoint extends Point {
int color = 0xFF00FF;
}
class Main {
public static void main(String[] args) throws Exception {
ColoredPoint cp = new ColoredPoint();
System.out.println(cp.color);
}
}
16711935
/* Example 12.5-2. Dynamic Dispatch During Instance Creation */
/* https://docs.oracle.com/javase/specs/jls/se11/html/jls-12.html#jls-12.5 */
import java.util.*;
class Super {
Super() { printThree(); }
void printThree() { System.out.println("three"); }
}
class Main extends Super {
int three = (int)Math.PI; // That is, 3
void printThree() { System.out.println(three); }
public static void main(String[] args) throws Exception {
Main t = new Main();
t.printThree();
}
}
0
3
Discussion