Java 相当于 C# 匿名数组和列表?

发布于 2024-10-13 15:15:32 字数 541 浏览 3 评论 0原文

当我需要将数组传递给函数时,C# 允许我即时创建数组。假设我有一个名为 findMiddleItem(String[] items) 的方法。在 C# 中,我可以编写如下代码:

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

这太棒了,因为这意味着我不必编写:

IList<String> strings = new List<String>();
strings.add("one");
strings.add("two");
strings.add("three");
findMiddleItem(strings.ToArray());

这很糟糕,因为我并不真正关心 string ——它只是一个让我将一个字符串数组传递给需要它的方法。我无法修改的方法。

那么如何在 Java 中做到这一点呢?我需要知道数组类型(例如 String[])和泛型类型(例如列表)的这一点。

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

星星的軌跡 2024-10-20 15:15:32

列表和数组是根本不同的东西。

列表是一个 集合 类型,接口的实现。
数组是一种特殊的操作系统特定数据结构,只能通过特殊语法或本机代码创建。

数组

在 Java 中,数组语法与您所描述的语法相同:

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

参考: Java 教程 >数组

列表

创建列表的最简单方法是这样的:

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

但是,生成的列表将是不可变的(或者至少它不支持 add()remove()),这样你就可以用 ArrayList 构造函数调用来包装调用:

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

正如 Jon Skeet 所说,Guava 更漂亮,你可以这样做:

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

参考:Java 教程 >列表接口列表 (guava javadocs)

VarArgs

关于此评论:

如果我们能够执行 findMiddleItem({ "one", "two", "third" }); 就太好了;

Java 可变参数为您提供了更好的选择:

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

您可以使用可变数量的参数来调用它:

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

或者使用数组:

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

参考:Java 教程 >任意数量的参数

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

烟─花易冷 2024-10-20 15:15:32

在Java中,你可以用同样的方式构造一个数组:

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

你不能以完全相同的方式构造一个List,但是有多种方法可以解决这个问题,例如包装一个数组,或使用一些 Guava Lists.* 方法。 (尝试使用 IList 类型的参数调用 findMiddleItem 的代码不会编译,因为 IListList 类型的参数,您可以使用:

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

不一定是 string[]。)例如,如果 findMiddleItem 实际上有一个 除了没有集合初始值设定项(或对象初始值设定项)之外,Java没有隐式类型数组...您的原始 C# 代码可以在 C# 3 及更高版本中压缩:

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

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" });
原谅我要高飞 2024-10-20 15:15:32

您可以按照完全相同的方式完成此操作:

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

在 Java 中有效。假设 findMiddleItem 定义为:

findMiddleItem(String[] array)

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)
甜`诱少女 2024-10-20 15:15:32

与 C# 中的方式相同 findMiddleItem(new String[] { "one", "two", "third" });

另外,为了将来的参考,您可以以稍微简洁的方式在 Java 中构造一个 List*

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

* 正如 Sean 指出的,这可以被认为是不好的做法,因为它确实创建了 ArrayList 的匿名子类。

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.

〃温暖了心ぐ 2024-10-20 15:15:32

我认为这与 Java 中的语法完全相同。这有效:

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

那些过往 2024-10-20 15:15:32

除了使用 vargs 之外,

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

您还可以进行

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

编辑:将字符串转换为列表,您可以使用辅助方法。

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

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

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"));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文