C# lets me make arrays on the fly when I need to pass them into functions. Let’s say I have a method called findMiddleItem(String[] items). In C#, I can write code like:
findMiddleItem(new String[] { "one", "two", "three" });
It’s awesome, because it means I don’t have to write:
IList<String> strings = new List<String>();
strings.add("one");
strings.add("two");
strings.add("three");
findMiddleItem(strings.ToArray());
Which sucks, because I don’t really care about strings — it’s just a construct to let me pass a string array into a method that requires it. A method which I can’t modify.
So how do you do this in Java? I need to know this for array types (eg. String[]) but also generic types (eg. List).
A List and an Array are fundamentally different things.
A
Listis aCollectiontype, an implementation of an interface.An Array is a special operating system specific data structure that can only be created through either a special syntax or native code.
Arrays
In Java, the array syntax is identical to the one you are describing:
Reference: Java tutorial > Arrays
Lists
The easiest way to create a List is this:
However, the resulting list will be immutable (or at least it won’t support
add()orremove()), so you can wrap the call with an ArrayList constructor call:As Jon Skeet says, it’s prettier with Guava, there you can do:
Reference:
Java Tutorial > The List Interface,Lists(guava javadocs)VarArgs
About this comment:
Java varargs gives you an even better deal:
you can call this using a variable number of arguments:
Or with an array:
Reference:
Java Tutorial > Arbitrary Number of Arguments