Java: What is the difference between these building methods

What is the difference between these two observer initialization methods of an ArrayList. Or any other type for that matter. Faster than the other? Or I missed some other catch here.

class Publisher implements Observerable
{
     private ArrayList observers = new ArrayList();
}

class Publisher implements Observerable
{
    private ArrayList observers; 

    public Publisher()
    {
        observers = new ArrayList();
    }
}
+5
source share
4 answers

They are equivalent. In fact, if you compile these two, you will see that they generate exactly the same bytecode:

Publisher();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   aload_0
   5:   new     #2; //class java/util/ArrayList
   8:   dup
   9:   invokespecial   #3; //Method java/util/ArrayList."<init>":()V
   12:  putfield        #4; //Field observers:Ljava/util/ArrayList;
   15:  return    
}

Given that they are the same code, there obviously cannot be any difference in speed :)

Please note that in C # they are not completely equivalent - in C # the initializer for observerswill be executed before the base constructor is called; in Java they are really the same.

, . , , . , , , "" , .

+13

, : , , : ..

+4

. , , . , , , .

:

:

public class Tester {
    Tester (String msg) {
        System.out.println(this + ":" + msg);

    }
}

:

public class Test  {

   protected Tester t1 = new Tester("super init block");

   Test (String constructorMsg) {
    new Tester(constructorMsg);
   }
}

:

Public class TestSub extends Test {

   private Tester t2 = new Tester("sub init block");

   TestSub(String constructorMsg) {
      super(constructorMsg);
      new TTester("sub constructor");
   }

}

main TestSub:

public static void main(String[] args) {
    new TestSub("super constructor");

}

:

Tester@3e205f:super init block
Tester@bf73fa:super constructor
Tester@5740bb:sub init block
Tester@5ac072:sub constructor
+2

. , , observers .

, .

+1

All Articles