Java 有什么方法可以在线声明数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1154008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:18:23  来源:igfitidea点击:

Any way to declare an array in-line?

javaarrays

提问by DivideByHero

Let's say I have a method m() that takes an array of Strings as an argument. Is there a way I can just declare this array in-line when I make the call? i.e. Instead of:

假设我有一个方法 m() 将字符串数组作为参数。有没有一种方法可以在我打电话时直接声明这个数组?即而不是:

String[] strs = {"blah", "hey", "yo"};
m(strs);

Can I just replace this with one line, and avoid declaring a named variable that I'm never going to use?

我可以只用一行替换它,并避免声明一个我永远不会使用的命名变量吗?

采纳答案by Draemon

m(new String[]{"blah", "hey", "yo"});

回答by Michael Myers

Draemon is correct. You can also declare mas taking varargs:

德拉蒙是对的。您还可以声明m为采用varargs

void m(String... strs) {
    // strs is seen as a normal String[] inside the method
}

m("blah", "hey", "yo"); // no [] or {} needed; each string is a separate arg here

回答by Bill K

I'd like to add that the array initialization syntax is very succinct and flexible. I use it a LOT to extract data from my code and place it somewhere more usable.

我想补充一点,数组初始化语法非常简洁和灵活。我经常使用它从我的代码中提取数据并将其放在更有用的地方。

As an example, I've often created menus like this:

例如,我经常创建这样的菜单:

Menu menu=initMenus(menuHandler, new String[]{"File", "+Save", "+Load", "Edit", "+Copy", ...});

This would allow me to write come code to set up a menu system. The "+" is enough to tell it to place that item under the previous item.

这将允许我编写代码来设置菜单系统。“+”足以告诉它将该项目放在前一项之下。

I could bind it to the menuHandler class either by a method naming convention by naming my methods something like "menuFile, menuFileSave, menuFileLoad, ..." and binding them reflectively (there are other alternatives).

我可以通过方法命名约定将它绑定到 menuHandler 类,方法是将我的方法命名为“menuFile、menuFileSave、menuFileLoad 等”,并反射性地绑定它们(还有其他替代方法)。

This syntax allows AMAZINGLY brief menu definition and an extremely reusable "initMenus" method. (Yet I don't bother reusing it because it's always fun to write and only takes a few minutes+a few lines of code).

这种语法允许非常简短的菜单定义和极其可重用的“initMenus”方法。(但我并不费心重用它,因为编写它总是很有趣,只需要几分钟+几行代码)。

any time you see a pattern in your code, see if you can replace it with something like this, and always remember how succinct the array initialization syntax is!.

任何时候你在代码中看到一个模式,看看你是否可以用这样的东西替换它,并且永远记住数组初始化语法是多么简洁!。

回答by Jonathan Weatherhead

As Draemon says, the closest that Java comes to inline arrays is new String[]{"blah", "hey", "yo"}however there is a neat trick that allows you to do something like

正如 Draemon 所说,Java 最接近内联数组的是,new String[]{"blah", "hey", "yo"}但是有一个巧妙的技巧可以让你做类似的事情

array("blah", "hey", "yo")with the type automatically inferred.

array("blah", "hey", "yo")类型自动推断。

I have been working on a useful API for augmenting the Java language to allow for inline arrays and collection types. For more details google project Espresso4J or check it out here

我一直在研究一个有用的 API,用于扩充 Java 语言以支持内联数组和集合类型。有关更多详细信息,请参阅谷歌项目 Espresso4J 或在此处查看

回答by Antonio Carlos

Another way to do that, if you want the result as a List inline, you can do it like this:

另一种方法是,如果您希望将结果作为内联列表,您可以这样做:

Arrays.asList(new String[] { "String1", "string2" });

回答by Mahpooya

You can create a method somewhere

你可以在某处创建一个方法

public static <T> T[] toArray(T... ts) {
    return ts;
}

then use it

然后使用它

m(toArray("blah", "hey", "yo"));

for better look.

为了更好看。

回答by Gibolt

You can directly write the array in modern Java, without an initializer. Your example is now valid. It is generally best to name the parameter anyway.

您可以直接用现代 Java 编写数组,而无需初始化程序。您的示例现在有效。通常最好以任何方式命名参数。

String[] array = {"blah", "hey", "yo"};

or

或者

int[] array = {1, 2, 3};

If you haveto inline, you'll need to declare the type:

如果必须内联,则需要声明类型:

functionCall(new String[]{"blah", "hey", "yo"});

or use varargs (variable arguments)

或使用可变参数(可变参数)

void functionCall(String...stringArray) {
    // Becomes a String[] containing any number of items or empty
}

functionCall("blah", "hey", "yo");

Hopefully Java's developers will allow implicit initialization in the future

但愿Java的开发人员将能够在隐式初始化未来

Update: Kotlin Answer

更新:Kotlin 答案

Kotlin has made working with arrays so much easier!For most types, just use arrayOfand it will implicitly determine type. Pass nothing to leave them empty.

Kotlin 使处理数组变得如此简单!对于大多数类型,只需使用arrayOf它就会隐式确定类型。什么都不通过,让它们空着。

arrayOf("1", "2", "3") // String
arrayOf(1, 2, 3)       // Int
arrayOf(1, 2, "foo")   // Any 
arrayOf<Int>(1, 2, 3)  // Set explict type
arrayOf<String>()      // Empty String array

Primitives have utility functions. Pass nothing to leave them empty.

原语具有效用函数。什么都不通过,让它们空着。

intArrayOf(1, 2, 3)
charArrayOf()
booleanArrayOf()
longArrayOf()
shortArrayOf()
byteArrayOf()

If you already have a Collectionand wish to convert it to an array inline, simply use:

如果您已经有 aCollection并希望将其转换为内联数组,只需使用:

collection.toTypedArray()

If you need to coerce an array type, use:

如果您需要强制转换数组类型,请使用:

array.toIntArray()
array.toLongArray()
array.toCharArray()
...

回答by Shravan Ramamurthy

Other option is to use ArrayUtils.toArray in org.apache.commons.lang3

其他选项是在 org.apache.commons.lang3 中使用 ArrayUtils.toArray

ArrayUtils.toArray("elem1","elem2")