定义数组时使用大括号

发布于 2025-01-02 00:12:48 字数 129 浏览 2 评论 0原文

关于以下代码:

int[] to = new int[] { text };

我理解它尝试定义一个整数数组,但是花括号在数组定义中起什么作用?

Regards to the following code:

int[] to = new int[] { text };

I understand it tries to define an array of integer, but What does the curly braces do in array definition?

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

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

发布评论

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

评论(5

蓝海 2025-01-09 00:12:48

这只是创建具有初始元素的数组的快捷方式代码,以下内容(相同):

    int[] to = new int[] { text };
    int[] to = { text };

可以替换为

    int[] to = new int[1];
    to[0] = text;

希望这会有所帮助。

This is just a shortcut code to create an array with initial elements, the followings (which are equal):

    int[] to = new int[] { text };
    int[] to = { text };

can be substituted with

    int[] to = new int[1];
    to[0] = text;

Hope this helps.

半岛未凉 2025-01-09 00:12:48

大括号包含填充数组的值。

The curly braces contain values to populate the array.

挽清梦 2025-01-09 00:12:48

此语法允许您定义数组的内容,通常称为数组文字。

在这种情况下,这实际上可以简化为:

int[] to = { 1, 2, 7, etc. };

仅当不属于赋值的一部分时才需要在其之前添加 new int[] ,例如:

someFunction(new int[]{1, 3, 5});

This syntax allows you to define the contents of an array and is often referred to as an array literal.

In this context this can actually be simplified to:

int[] to = { 1, 2, 7, etc. };

Adding new int[] before it is only required when not part of an assignment, something like:

someFunction(new int[]{1, 3, 5});
禾厶谷欠 2025-01-09 00:12:48

大括号向编译器表示数组的值

Curly braces said to the compiler the values of the array

_失温 2025-01-09 00:12:48

正如 SLaks 所说,花括号是 Java 表示集合的一种方式。您可以使用此方法定义数组的内容,但您定义的每个元素必须与数组具有相同的类型。

Like SLaks said, curly braces is a way Java denotes a set. You can define the contents of the array using this method, but each element you define has to be the same type as the array.

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