我知道这可能很基本,也可能很直接,但我无法清楚地理解在这种情况下会发生什么,所以,就这样吧。
在以下代码中:
String str1 = "Hello";
String str2 = "World";
String str3 = new String("HelloWorld");
String str4 = str1 + str2;
Run Code Online (Sandbox Code Playgroud)
我知道 str1 和 str2 将在String Constant Pool内分别创建一个对象“Hello”和“World” 。对于 str3,在String Constant Pool外部创建了一个新对象,该对象指向在String Constant Pool内部创建的“HelloWorld” 。
我的问题是,如果我连接 2 个或更多字符串(使用 '+' 或 concat() 方法)会发生什么?
是否会像String str3一样在池外创建一个新对象,或者 str4 将直接指向String Constant Pool内的对象“HelloWorld”
PS:如果它是在池外创建新对象的情况,那么不使用new关键字如何发生?
byte b =10;
int a = b; // Primitive data type widening
// Works perfectly fine
Run Code Online (Sandbox Code Playgroud)
上面的代码不会给出任何错误/警告.但为什么同样不适用于下面提到的代码?
byte[] b = new byte[10];
int[] i1 = b; //Cannot convert from byte[] to int[]
int[] i2 = new byte[10]; //Cannot convert from byte[] to int[]
Run Code Online (Sandbox Code Playgroud)
我的问题是,因为int可以保存任何和所有字节值,为什么这不是数组的情况?
他们都在拿着地址.如果这对于ref变量是可能的,那么这将是向上的.
我有这个代码:
@Override
public boolean equals(Object obj) {
System.out.println("equals called");
if(this == obj) {
System.out.println("THIS object is the same as OBJ");
return true;
}
System.out.println("obj.getClass() is " + obj.getClass());
System.out.println("this.getClass() is " + this.getClass());
if ((obj == null) || (obj.getClass() != this.getClass())) {
return false;
}
double objOrbitalPeriod = ((HeavenlyBody) obj).getOrbitalPeriod();
return this.orbitalPeriod == objOrbitalPeriod;
}
@Override
public int hashCode() {
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在主要代码是:
private static Set<Planet> solarSystem = new HashSet<>();
public static void main(String[] args) {
Planet planet = …
Run Code Online (Sandbox Code Playgroud) 假设我正在写一个包.我有以下继承层次结构,都在我的包中:
public class Container {
public void size() {
System.out.println(10);
}
}
public final class Bucket extends Container {}
public final class Bag extends Container {}
public class Item {
Container container; // is aware of what container it's in. Will be initialized on construction.
public Container getContainer() {
return container;
}
}
Run Code Online (Sandbox Code Playgroud)
我想阻止其他人进行子类化Container
.但我不能让它final
因为Bucket
和Bag
是子类.我必须做到这一点public
,否则外人不能打电话getContainer()
.有没有办法在Java中这样做?否则,人们在这种情况下做了什么?