In Java anonymous inner classes are used for a more concise method of double bracket initialization

  • 2020-04-01 01:38:38
  • OfStack

Java's collection collection frameworks such as set, map, and list do not provide any easy way to initialize. Each time you set up a collection, you add the values one by one. Such as


Set<Character> letter=new HashSet<Character>();
letter.add('a');
letter.add('b');
//...

It's very tedious.

But with anonymous inner classes. It could be a little easier.


Set<Character> letter=new HashSet<Character>()
  {
   {
    add('a'); add('b'); add('c'); add('d');
       add('e'); add('f'); add('g'); add('h');
       add('i'); add('j'); add('k'); add('l');
       add('m'); add('n'); add('o'); add('p'); 
       add('q'); add('r'); add('s'); add('t'); 
       add('u'); add('v'); add('w'); add('x');
       add('y'); add('z');
       add('A'); add('B'); add('C'); add('D');
       add('E'); add('F'); add('G'); add('H');
       add('I'); add('J'); add('K'); add('L');
       add('M'); add('N'); add('O'); add('P');
       add('Q'); add('R'); add('S'); add('T');
       add('U'); add('V'); add('W'); add('X');
       add('Y'); add('Z');
   }
  };  //The first bracket defines the anonymous inner class, and the second is the initialization module

 


Related articles: