how to initialize static ArrayList in one line

后端 未结 6 431
醉话见心
醉话见心 2020-12-24 12:50

i have MyClass as

MyClass(String, String, int);

i know about how to add to add to ArrayList in this way:

MyClass.name = \"N         


        
6条回答
  •  我在风中等你
    2020-12-24 13:22

    You can instantiate ArrayList like so:

    new ArrayList() {{
      add(new MyClass("Name", "Address", age));
    }};
    

    This creates an anonymous inner class that actually extends ArrayList, with an initialiser block that calls add. This is obviously completely filthy and will make your colleagues want to hurt you, so you should use Arrays.asList instead. :)

提交回复
热议问题