Java中的匿名数组

Java中的数组 没有名字 被称为 匿名数组 。这是一个数组,仅用于即时创建和使用。使用匿名数组,我们可以传递带有用户值的数组,而不需要引用变量。

null

匿名数组的属性:

  • 我们可以创建一个没有名称的数组。这种类型的无名数组称为匿名数组。
  • 匿名数组的主要用途仅用于即时使用(仅用于一次性使用)。
  • 匿名数组作为方法的参数传递。

注: 对于匿名数组创建,请不要在[]中提及大小。在{}内传递的值的数量将成为大小。

语法:

new <data type>[]{<list of values with comma separator>};

例如:

// anonymous int array new int[] { 1, 2, 3, 4};  // anonymous char array new char[] {'x', 'y', 'z'); // anonymous String arraynew String[] {"Geeks", "for", "Geeks"}; // anonymous multidimensional arraynew int[][] { {10, 20}, {30, 40, 50} };

实施:

JAVA

// Java program to illustrate the
// concept of anonymous array
class Test {
public static void main(String[] args)
{
// anonymous array
sum( new int []{ 1 , 2 , 3 });
}
public static void sum( int [] a)
{
int total = 0 ;
// using for-each loop
for ( int i : a)
total = total + i;
System.out.println( "The sum is: " + total);
}
}


输出

The sum is: 6

说明: 在上面的例子中,为了调用sum方法,我们需要一个数组,但是在实现sum方法之后,我们不再使用数组。因此,对于这种一次性需求,匿名数组是最佳选择。根据我们的要求,我们可以稍后为匿名数组命名,这样它就不再是匿名数组了。

本文由 比沙尔·库马尔·杜比 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享