[英]Java Equivalent of C# Anonymous Arrays and Lists?
C# lets me make arrays on the fly when I need to pass them into functions. 当我需要将它们传递给函数时,C#允许我动态创建数组。 Let's say I have a method called
findMiddleItem(String[] items)
. 假设我有一个名为
findMiddleItem(String[] items)
。 In C#, I can write code like: 在C#中,我可以编写如下代码:
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. 这很糟糕,因为我并不真正关心
strings
- 它只是一个让我将字符串数组传递给需要它的方法的构造。 A method which I can't modify. 一种我无法修改的方法。
So how do you do this in Java? 那么你如何用Java做到这一点? I need to know this for array types (eg. String[]) but also generic types (eg. List).
我需要知道数组类型(例如String [])以及泛型类型(例如List)。
A List and an Array are fundamentally different things. List和Array是根本不同的东西。
A List
is a Collection
type, an implementation of an interface. List
是Collection
类型,是接口的实现。
An Array is a special operating system specific data structure that can only be created through either a special syntax or native code. Array是一种特殊的操作系统特定数据结构,只能通过特殊语法或本机代码创建。
In Java, the array syntax is identical to the one you are describing: 在Java中,数组语法与您描述的语法相同:
String[] array = new String[] { "one", "two", "three" };
Reference: Java tutorial > Arrays 参考: Java教程>数组
The easiest way to create a List is this: 创建List的最简单方法是:
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: 但是,结果列表将是不可变的(或者至少它不支持
add()
或remove()
),因此您可以使用ArrayList构造函数调用来包装调用:
new ArrayList<String>(Arrays.asList("one", "two", "three"));
As Jon Skeet says, it's prettier with Guava, there you can do: 正如Jon Skeet所说,它与番石榴相比更漂亮,你可以做到:
Lists.newArrayList("one", "two", "three");
Reference: Java Tutorial > The List Interface
, Lists
(guava javadocs) 参考:
Java Tutorial > The List Interface
, Lists
(guava javadocs)
About this comment: 关于这个评论:
It would be nice if we would be able to do findMiddleItem({ "one", "two", "three" });
如果我们能够做findMiddleItem({“one”,“two”,“three”})会很好;
Java varargs gives you an even better deal: Java varargs为您提供了更好的交易:
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
参考:
Java Tutorial > Arbitrary Number of Arguments
You can do it the exact same way: 你可以用完全相同的方式做到:
findMiddleItem(new String[] { "one", "two", "three" });
is valid in Java. 在Java中有效。 Assuming that
findMiddleItem
is defined as: 假设
findMiddleItem
定义为:
findMiddleItem(String[] array)
In Java you can construct an array in the same way: 在Java中,您可以以相同的方式构造数组:
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, eg wrapping an array, or using some of the Guava Lists.*
methods. 你不能以完全相同的方式构造
List<T>
,但是有各种方法可以解决这个问题,例如包装数组或使用一些Guava Lists.*
方法。 (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: (您尝试使用
IList<string>
类型的参数调用findMiddleItem
代码将不会编译,因为IList<string>
不一定是string[]
。)例如,如果findMiddleItem
实际上具有List<String>
类型的参数您可以使用List<String>
:
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: 除了没有集合初始化器(或对象初始化器)之外,Java 也没有隐式类型化的数组......您的原始C#代码可以在C#3及更高版本中压缩:
findMiddleItem(new[] { "one", "two", "three" });
The same way as in C# findMiddleItem(new String[] { "one", "two", "three" })
; 与C#
findMiddleItem(new String[] { "one", "two", "three" })
;
Also, for future reference, you can construct a List in Java in a slightly less-verbose way * : 此外,为了将来参考,您可以用稍微冗长的方式在Java中构建List * :
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
. *正如Sean所指出的,这可以被认为是不好的做法,因为它确实创建了一个
ArrayList
的匿名子类。
I think it's the exact same syntax in Java. 我认为这是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 除了使用vargs之外
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. 编辑:要将String转换为List,您可以使用辅助方法。
public static List<String> list(String text) {
return Arrays.asList(text.split(","));
}
findMiddleItem(list("one,two,three,four,five"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.