Strange string array declaration Syntax

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

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



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({

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).

Need Your Help

Access Google Spreadsheet or Google Data API only with Javascript

javascript jquery google-api google-spreadsheet google-data-api

I want to access Google Spreadsheets using JavaScript Only. ( no .NET C#, Java )

Scrolling crashes program when scrolling through grid view

java android

When I try to scroll through my word search, my program crashes throwing a null pointer exception.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.