C
C
Che_Bu_Rashka2017-03-18 10:20:59
Java
Che_Bu_Rashka, 2017-03-18 10:20:59

What are double curly braces in code?

Here is a piece of code, its essence is not important.

public List<SelectItem> filterOptions = new ArrayList<SelectItem>() {{
        add(new SelectItem("Van"));
        add(new SelectItem("Bus"));
        add(new SelectItem("Compact"));
        add(new SelectItem("Semi-Truck"));
        add(new SelectItem("Pickup"));
    }};

What are double curly braces? Explain. Doesn't work without them. What is this syntax when applied?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Eugene Khrustalev, 2017-03-18
@Che_Bu_Rashka

It is better to write it down so that it is clearer.

public List<SelectItem> filterOptions = new ArrayList<SelectItem>() {
    // anonymous constructor()
    {
        add(new SelectItem("Van"));
        add(new SelectItem("Bus"));
        add(new SelectItem("Compact"));
        add(new SelectItem("Semi-Truck"));
        add(new SelectItem("Pickup"));
    }
};

An anonymous child class from ArrayList is created here and its constructor is called (also, by the way, without a name)

A
Anton, 2017-03-18
@sHinE

Apparently - the initialization block - https://habrahabr.ru/post/133237/ the first section.
PS I'm by no means an expert on java.

C
Che_Bu_Rashka, 2017-03-18
@Che_Bu_Rashka

Thanks for enlightening me. How many more subtleties. any...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question