小编Ari*_*pta的帖子

当使用静态引用创建对象时,为什么在静态块之前执行实例块和默认构造函数?

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的静态块之前执行?

java static-block

6
推荐指数
1
解决办法
681
查看次数

字符串常量池和实习生

我最近几天试图理解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

java string string-literals

6
推荐指数
1
解决办法
750
查看次数

为什么即使我们可以使用以下代码段进行深度克隆,我们也会实现Cloneable

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克隆吗?以上程序是一种深度克隆吗?

java clone interface cloneable cloning

5
推荐指数
1
解决办法
1796
查看次数

实习生如何在以下代码中工作?

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

java string literals

5
推荐指数
2
解决办法
110
查看次数

如何在 TreeSet 或 TreeMap 中添加 ArrayList 元素

众所周知,在使用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 collections dictionary set comparable

2
推荐指数
1
解决办法
9194
查看次数