我有一个奇怪的字符串池行为的问题.我==用来比较相同的字符串,以确定它们是否在池中.
public class StringPoolTest {
public static void main(String[] args) {
new StringPoolTest().run();
}
String giveLiteralString() {
return "555";
}
void run() {
String s1 = giveLiteralString() + "";
System.out.println("555" == "555" + "");
System.out.println(giveLiteralString() == giveLiteralString() + "");
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
true
false
Run Code Online (Sandbox Code Playgroud)
这对我来说是个大惊喜.有人能解释一下吗?我认为这个问题发生在编译时.但是为什么添加""到String会产生任何差异呢?
这个问题是关于良好的编程实践和避免潜在的漏洞.
我读了Joshua Bloch的Effective Java,这就是我想知道的:
为什么我要考虑在我的不可变类中使用getter方法制作防御性副本而不使用mutator?
第二:除了私人之外,我为什么要让我的领域最终成绩?这只是关于性能(不是安全性)吗?
例如,我们有一个静态ThreadLocal字段和一个setter:
private static final ThreadLocal threadLocalField = new ThreadLocal;
public static void getSXTransaction() {
threadLocalField.set(new MyValue());
}
Run Code Online (Sandbox Code Playgroud)
我想知道,由于java.lang.ThreadLocal #set方法中没有隐式同步,所以线程安全的保证是什么?我知道TreadLocal类本质上是完全线程安全的,但是我无法理解它是如何实现的.
这是它的源代码:
/**
* Sets the current thread's copy of this thread-local variable
* to the specified value. Most subclasses will have no need to
* override this method, relying solely on the {@link #initialValue}
* method to set the values of thread-locals.
*
* @param value the value to be stored in the current thread's copy of
* this …Run Code Online (Sandbox Code Playgroud) 可能重复:
首选组合而不是继承?
我想知道,为什么(或者在哪种情况下)应该考虑继承而不是组合,当它有这么多的缺点时:
因此,我无法想象,地球上我们如何依赖它.超类作者可能希望提高性能,我们的客户端代码可能会崩溃.
所以我的问题是:
关于Java的基础知识,我遇到了一件有趣的事情.这是代码:
class Whoa {
private int n;
private void d() {
Whoa whoa = new Whoa();
whoa.n = 1;
}
}
Run Code Online (Sandbox Code Playgroud)
为什么n对象的字段whoa可以访问?我的意思是,好吧,我们在课堂上.但是whoa是单独的对象,我以为我们只能访问当前对象的字段.虽然我承认如果我们有一个采用Whoa参数的方法:
private void b(Whoa w) {
w.n = 20;
}
Run Code Online (Sandbox Code Playgroud)
我们肯定可以访问n.这一切都让人很困惑.有人可以澄清一下吗?