开发者

Java Equivalent of C# Anonymous Arrays and Lists?

开发者 https://www.devze.com 2023-02-05 14:18 出处:网络
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:

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 开发者_JAVA百科this for array types (eg. String[]) but also generic types (eg. List).


A List and an Array are fundamentally different things.

A List is a Collection type, 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:

String[] array = new String[] { "one", "two", "three" };

Reference: Java tutorial > Arrays

Lists

The easiest way to create a List is this:

List<String> list = Arrays.asList("one", "two", "three");

However, the resulting list will be immutable (or at least it won't support add() or remove()), so you can wrap the call with an ArrayList constructor call:

new ArrayList<String>(Arrays.asList("one", "two", "three"));

As Jon Skeet says, it's prettier with Guava, there you can do:

Lists.newArrayList("one", "two", "three");

Reference: Java Tutorial > The List Interface, Lists (guava javadocs)

VarArgs

About this comment:

It would be nice if we would be able to do findMiddleItem({ "one", "two", "three" });

Java varargs gives you an even better deal:

public void findMiddleItem(String ... args){
    //
}

you can call this using a variable number of arguments:

findMiddleItem("one");
findMiddleItem("one", "two");
findMiddleItem("one", "two", "three");

Or with an array:

findMiddleItem(new String[]{"one", "two", "three"});

Reference: Java Tutorial > Arbitrary Number of Arguments


In Java you can construct an array in the same way:

findMiddleItem(new String[] { "one", "two", "three" });

You can't construct a List<T> in quite the same way, but there are various ways of getting around that, e.g. wrapping an array, or using some of the Guava Lists.* methods. (Your code trying to call findMiddleItem with an argument of type IList<string> wouldn't have compiled, as an IList<string> isn't necessarily a string[].) For example, if findMiddleItem actually had a parameter of type List<String> you could use:

findMiddleItem(Lists.newArrayList("one", "two", "three"));

As well as not having collection initializers (or object initializers), Java also doesn't have implicitly typed arrays... your original C# code can be condensed in C# 3 and higher:

findMiddleItem(new[] { "one", "two", "three" });


You can do it the exact same way:

findMiddleItem(new String[] { "one", "two", "three" });

is valid in Java. Assuming that findMiddleItem is defined as:

findMiddleItem(String[] array)


The same way as in C# findMiddleItem(new String[] { "one", "two", "three" });

Also, for future reference, you can construct a List in Java in a slightly less-verbose way*:

List<String> myStringList = new ArrayList<String>() {{
   add("a");
   add("b");
   add("c");
}};

* As Sean pointed out, this can be considered bad practice since it does create an anonymous subclass of ArrayList.


I think it's the exact same syntax in Java. This works:

public class Main
{
    public static void main( String[] args )
    {
        method1( new String[] {"this", "is", "a", "test"} );
    }


    private static void method1( String[] params )
    {
        for( String string : params )
            System.out.println( string );
    }
}

I think this will work on non-static methods, too.


Apart from using vargs like

findMiddleItem("one", "two", "three", "four", "five");

you can do

findMiddleItem("one,two,three,four,five".split(","));

EDIT: to turn a String into a List you can use a helper method.

public static List<String> list(String text) {
    return Arrays.asList(text.split(","));
}

findMiddleItem(list("one,two,three,four,five"));
0

精彩评论

暂无评论...
验证码 换一张
取 消