Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange string array declaration Syntax

private final String[] okFileExtensions = new String[] { "csv" };

Would someone please explain why {} is written after a String array declaration?

Thanks.

like image 790
bob Avatar asked Jan 11 '10 15:01

bob


3 Answers

It's an array of one element. In this case containing the String "csv".

When written as part of a declaration, this can be written in a more concise form:

private final String[] okFileExtensions = { "csv" };

Multiple-element arrays use commas between values. There needn't be any values at all.

private final String[] okFileExtensions = { "csv", "tsv" };

private final String[] noFileExtensions = { };

It may be worth noting that although the reference is final the array is not. So you can write:

    okFileExtensions[0] = "exe";

A way to get around this is to switch to collections and use an unmodifiable implementation:

private final Set<String> okFileExtensions = Collections.unmodifiableSet(
    new HashSet<String>(Arrays.asList({
        "csv"
    }));

JDK8 is intended to have enhancement to collections that will make this more concise. Probably List and Set literals within the language. Possibly:

private final Set<String> okFileExtensions = { "csv" };

Collections should generally be preferred over arrays (for reference types).

like image 83
Tom Hawtin - tackline Avatar answered Oct 15 '22 02:10

Tom Hawtin - tackline


That's the Java's valid syntax for array declaration.

You may use that when you are passing an array without declaring a variable:

 public void printArray( String [] someArray ) {
      for( String s : someArray) {
          System.out.println( s );
      }
  }

And invoke it like this:

  printArray( new String [] { "These", "are", "the", "contents"} );

The curly braces can only be used when declaring the array so the following is not allowed:

Stirng [] a;

a = {"on", "two"};
like image 40
OscarRyz Avatar answered Oct 15 '22 01:10

OscarRyz


Creating an array of strings inline.

like image 34
Finglas Avatar answered Oct 15 '22 02:10

Finglas