Code block of anonymous object in Java
Posted SamDlex
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Code block of anonymous object in Java相关的知识,希望对你有一定的参考价值。
I came across this way of coding:
List<String> lsit = new ArrayList<String>()
add("hello world");
add("China!");
add("The Great Wall!");
;
I have never coded like this. But I think it is good way to initial the list object. In recent days,I call an API,which needs an list object as a parameter. The traditional way is to create a List object first,then call its add method to add my parameter,and pass onto the API.
It is convenient to create an anonymous List object ,and use a code block to add the paramed which needed by the API. So let’s talk about the code block.
Here is A class:
public class A
public A()
System.out.println("Hello 8888");
// Here is a code block
System.out.println("Hello world");
You know what! The code block is going to be executed after the constructor of A is executed. The output of A object looks like this:
Hello 8888
We can make use of the feature. I assume that we have a function or method like the following:
public float getPriceOfFruit(List<Fruit> list)
...
Now we can do like this:
List<Fruit> list = new ArrayList<Fruit>()
add(new Apple());
add(new Pear());
add(new Organe())
;
float total = getPriceOfFruit(list);
As you see that. It is convenient to use this way to initialize the parameter.
以上是关于Code block of anonymous object in Java的主要内容,如果未能解决你的问题,请参考以下文章
hiveserver2连接报错: User: root is not allowed to impersonate anonymous (state=08S01,code=0)
Code::Blockswindows 环境下编译 Code::Blocks(已修正)
bad geometry: block count 65536 exceeds size of device (53248 blocks)