public class TestLab {
static Test aStatic=new Test();
public static void main(String[] args) {
TestLab obj=new TestLab();
}
static{
System.out.println("In static block of TestLab");
}
}
public class Test {
static Test ref=new Test();
Test()
{
System.out.println("Default Constructor of Test");
}
static
{
System.out.println("In Static Block of Test");
}
{
System.out.println("In instance block of Test");
}
}
Run Code Online (Sandbox Code Playgroud)
通常,在类加载期间首先执行静态块.执行上面的示例时,会收到以下输出:
在测试的实例块中
默认的测试构造函数
在静态测试块中
在测试的实例块中
默认的测试构造函数
在TestLab的静态块中
为什么Test类的实例块和Default Constructor在Test Class的静态块之前执行?
我最近几天试图理解String常量池和inter的概念,在阅读了很多文章之后我理解了它的一些部分,但仍然对以下几点感到困惑: -
1. String a = "abc"
这会在字符串常量池中创建一个对象,但是以下代码行是否在字符串常量池中创建对象"xyz"?
String b = ("xyz").toLowerCase()
2.
String c = "qwe"
String d = c.substring(1)
d.intern()
String e = "we"
Run Code Online (Sandbox Code Playgroud)
在类加载期间是否应将字符"we"添加到String consant池中,如果是这样,为什么d==e
即使d未指向String Constant池也会返回true
public class Color {
String color;
Color(String color)
{
this.color=color;
}
}
public class ColoredCircle {
int x;
Color color;
ColoredCircle(int x, Color color)
{
this.x=x;
this.color=color;
}
public Object testClone()
{
Color c = new Color(this.color.color);
ColoredCircle cc1 = new ColoredCircle(this.x, c);
return cc1;
}
}
Run Code Online (Sandbox Code Playgroud)
在上面提到的ColoredCircle类中,我们有一个名为testClone()的方法,它与Deep Cloning完全相同.现在我很困惑,有必要实现Cloneable克隆吗?以上程序是一种深度克隆吗?
String a = "abc";
String b = a.substring(1);
b.intern();
String c = "bc";
System.out.println(b == c);
Run Code Online (Sandbox Code Playgroud)
问题可能是愚蠢的,因为实习生在这里没有主要用法,我仍然对这个事实感到困惑,为什么会有b == c
结果true
.
什么时候
String b = a.substring(1)
Run Code Online (Sandbox Code Playgroud)
执行,String b
对象的引用"bc"
是否在String Constant池中b.intern
创建文字"bc"
,即使它确实如此,怎么会b==c
产生true
?
众所周知,在使用TreeSet时,我们需要实现Comparable接口并添加compareTo()。不这样做将会抛出 ClassCastException。现在我有一个 TreeSet,我需要添加 ArrayList 作为 TreeSet 的元素。
如果我们写:
ArrayList al = new ArrayList();
ArrayList al2 = new ArrayList();
ArrayList al3 = new ArrayList();
TreeSet ts = new TreeSet();
ts.add(al);
ts.add(al2);
ts.add(al3);
Run Code Online (Sandbox Code Playgroud)
它抛出 ClassCastException。
问题:如何将 ArrayList 实例(而不是其元素)添加到 TreeSet 或 TreeMap?
java ×5
string ×2
clone ×1
cloneable ×1
cloning ×1
collections ×1
comparable ×1
dictionary ×1
interface ×1
literals ×1
set ×1
static-block ×1