Create Inline array in Java

In Java, sometimes, we want to create to pass an array to as an argument without explicitly creating a variable to hold a reference to the array. We can do this like:

Instead of

String choices [] = {"Create a Plate","Delete a Plate","View Plates","Get Receipt"};
ChoiceFactory.getChoice(choices);

We can just do:

ChoiceFactory.getChoice(new String[] {"Create a Plate","Delete a Plate","View Plates","Get Receipt"});

Similarly, we can do the same for a list,

List acceptedTypes = new ArrayList(){{add("Kingdom");add("Class");add("Order");add("Phylum");add("Species");add("Genus");add("Family");}};

Simple :)

Speak Your Mind

*