Tricky Tricks ›› Programming Tricks ›› Java Tricks ›› Anonymous Arrays

Anonymous Arrays

Java Programming Tricks

Anonymous arrays:

 
 You can supply initial values to an array as follows: 
 
 int[] primes = { 2, 3, 5, 7, 11, 13 };
 

If a function requires array parameters, then the traditional solution is to define and initialize an array variable and pass it to the function. For example, the getTables method of the DatabaseMetadata class requires an array of strings "TABLE", "VIEN", "ALIAS", ... to describe which kinds of tables are requested.

 String [] tables = ( "TABLE", "VIEW" ); 
 
 md.getTables(null, "%", "%", tables); 
 
 Tip 
 
 Rather than introducing a new variable that is only used once, use an anonymaus array 
 
 new Type [] ( value1, value2, ... ) 
 
 In our example, 
 
 md.getTables (null, "%", "%", new String[] { "TABLE", "VIEW" ) ) 
 
  
 

Partners