What is Double Brace initialization in Java?

前端 未结 13 2263
旧时难觅i
旧时难觅i 2020-11-21 07:22

What is Double Brace initialization syntax ({{ ... }}) in Java?

13条回答
  •  再見小時候
    2020-11-21 08:05

    To avoid all negative effects of double brace initialization, such as:

    1. Broken "equals" compatibility.
    2. No checks performed, when use direct assignments.
    3. Possible memory leaks.

    do next things:

    1. Make separate "Builder" class especially for double brace initialization.
    2. Declare fields with default values.
    3. Put object creation method in that class.

    Example:

    public class MyClass {
        public static class Builder {
            public int    first  = -1        ;
            public double second = Double.NaN;
            public String third  = null      ;
    
            public MyClass create() {
                return new MyClass(first, second, third);
            }
        }
    
        protected final int    first ;
        protected final double second;
        protected final String third ;
    
        protected MyClass(
            int    first ,
            double second,
            String third
        ) {
            this.first = first ;
            this.second= second;
            this.third = third ;
        }
    
        public int    first () { return first ; }
        public double second() { return second; }
        public String third () { return third ; }
    }
    

    Usage:

    MyClass my = new MyClass.Builder(){{ first = 1; third = "3"; }}.create();
    

    Advantages:

    1. Simply to use.
    2. Do not breaks "equals" compatibility.
    3. You can perform checks in creation method.
    4. No memory leaks.

    Disadvantages:

    • None.

    And, as a result, we have simplest java builder pattern ever.

    See all samples at github: java-sf-builder-simple-example

提交回复
热议问题