简体   繁体   English

java 中的 new String[]{} 和 new String[] 之间的区别

[英]difference between new String[]{} and new String[] in java

I am fresher in java,i have a doubt in java that is我对 java 比较新鲜,我对 java 有疑问

String array= new String[]{};
  1. what is the use of { } here? { }在这里有什么用?
  2. what is the difference between String array=new String[]; String array=new String[];有什么区别? and String array=new String[]{};String array=new String[]{};
  3. when I am writing String array=new String[10]{};当我写String array=new String[10]{}; got error why?有错误为什么? Help me I am confused.帮帮我,我很困惑。

{} defines the contents of the array, in this case it is empty. {}定义数组的内容,在本例中为空。 These would both have an array of three String s它们都有一个包含三个String的数组

String[] array = {"element1","element2","element3"};
String[] array = new String[] {"element1","element2","element3"};

while [] on the expression side (right side of = ) of a statement defines the size of an intended array, eg this would have an array of 10 locations to place String s而语句的表达式侧( =右侧[]上的[]定义了预期数组的大小,例如,这将有一个包含 10 个位置的数组来放置String s

String[] array = new String[10];

...But... ……但是……

String array = new String[10]{};  //The line you mentioned above

Was wrong because you are defining an array of length 10 ( [10] ), then defining an array of length 0 ( {} ), and trying to set them to the same array reference ( array ) in one statement.错了,因为您定义了一个长度为 10 ( [10] ) 的数组,然后定义了一个长度为 0 ( {} ) 的数组,并试图在一个语句中将它们设置为相同的数组引用 ( array )。 Both cannot be set.两者都不能设置。

Additionally另外

The array should be defined as an array of a given type at the start of the statement like String[] array .该数组应在语句的开头定义为给定类型的数组,例如String[] array String array = /* array value*/ is saying, set an array value to a String , not to an array of String s. String array = /* array value*/是说,将数组值设置为String ,而不是String的数组。

String array=new String[]; and String array=new String[]{};String array=new String[]{}; both are invalid statement in java.两者都是java中的无效语句。

It will gives you an error that you are trying to assign String array to String datatype.它会给您一个错误,提示您尝试将String array分配给String数据类型。 More specifically error is like this Type mismatch: cannot convert from String[] to String更具体地说,错误是这样的Type mismatch: cannot convert from String[] to String

You have a choice, when you create an object array (as opposed to an array of primitives).当您创建对象数组(而不是原始数组)时,您有一个选择。

One option is to specify a size for the array, in which case it will just contain lots of nulls.一种选择是指定数组的大小,在这种情况下,它将只包含大量空值。

String[] array = new String[10]; // Array of size 10, filled with nulls.

The other option is to specify what will be in the array.另一个选项是指定数组中的内容。

String[] array = new String[] {"Larry", "Curly", "Moe"};  // Array of size 3, filled with stooges.

But you can't mix the two syntaxes.但是您不能混合使用这两种语法。 Pick one or the other.选择其中之一。

TL;DR TL; 博士

  • An array variable has to be typed T[]数组变量的类型必须是T[]
    (note that T can be an arry type itself -> multidimensional arrays) (请注意, T 本身可以是 arry 类型 -> 多维数组)
  • The length of the array must be determined either by:数组的长度必须由以下任一确定:
    • giving it an explicit size给它一个明确的大小
      (can be int constant or int expression, see n below) (可以是int常量或int表达式,见下面的n
    • initializing all the values inside the array初始化数组中的所有值
      (length is implicitly calculated from given elements) (长度是根据给定元素隐式计算的)
  • Any variable that is typed T[] has one read-only field: length and an index operator [int] for reading/writing data at certain indices.任何类型为T[]变量都有一个只读字段: length和一个索引运算符[int]用于在某些索引处读取/写入数据。

Replies回复

1. String[] array= new String[]{}; 1. String[] array= new String[]{}; what is the use of { } here ? { } 在这里有什么用?

It initializes the array with the values between { } .它使用{ }之间的值初始化数组。 In this case 0 elements, so array.length == 0 and array[0] throws IndexOutOfBoundsException: 0 .在这种情况下 0 个元素,因此array.length == 0array[0] throws IndexOutOfBoundsException: 0

2. what is the diff between String array=new String[]; 2. String array=new String[];的区别是什么String array=new String[]; and String array=new String[]{};String array=new String[]{};

The first won't compile for two reasons while the second won't compile for one reason.第一个不会编译有两个原因,而第二个不会编译有一个原因。 The common reason is that the type of the variable array has to be an array type: String[] not just String .常见的原因是变量数组的类型必须是数组类型: String[]而不仅仅是String Ignoring that (probably just a typo) the difference is:忽略(可能只是一个错字)的区别是:

new String[]   // size not known, compile error
new String[]{} // size is known, it has 0 elements, listed inside {}
new String[0]  // size is known, it has 0 elements, explicitly sized

3. when am writing String array=new String[10]{}; 3. 当我在写String array=new String[10]{}; got error why ?为什么出错?

(Again, ignoring the missing [] before array ) In this case you're over-eager to tell Java what to do and you're giving conflicting data. (同样,忽略array之前缺少的[] )在这种情况下,您过于急于告诉 Java 做什么,并且您提供了相互冲突的数据。 First you tell Java that you want 10 elements for the array to hold and then you're saying you want the array to be empty via {} .首先,您告诉 Java 您希望数组包含 10 个元素,然后通过{}说您希望数组为空。 Just make up your mind and use one of those - Java thinks.只要下定决心并使用其中之一 - Java 认为。

help me i am confused帮帮我,我很困惑

Examples例子

String[] noStrings = new String[0];
String[] noStrings = new String[] { };
String[] oneString = new String[] { "atIndex0" };
String[] oneString = new String[1];
String[] oneString = new String[] { null }; // same as previous
String[] threeStrings = new String[] { "atIndex0", "atIndex1", "atIndex2" };
String[] threeStrings = new String[] { "atIndex0", null, "atIndex2" }; // you can skip an index
String[] threeStrings = new String[3];
String[] threeStrings = new String[] { null, null, null }; // same as previous
int[] twoNumbers = new int[2];
int[] twoNumbers = new int[] { 0, 0 }; // same as above
int[] twoNumbers = new int[] { 1, 2 }; // twoNumbers.length == 2 && twoNumbers[0] == 1 && twoNumbers[1] == 2
int n = 2;
int[] nNumbers = new int[n]; // same as [2] and { 0, 0 }
int[] nNumbers = new int[2*n]; // same as new int[4] if n == 2

(Here, "same as" means it will construct the same array.) (这里,“same as”意味着它将构造相同的数组。)

Try this one.试试这个。

  String[] array1= new String[]{};
  System.out.println(array1.length);
  String[] array2= new String[0];
  System.out.println(array2.length);

Note: there is no byte code difference between new String[]{};注意:new String[]{} 之间没有字节码区别; and new String[0];和新的字符串[0];

new String[]{} is array initialization with values. new String[]{}是带值的数组初始化。

new String[0]; is array declaration(only allocating memory)是数组声明(只分配内存)

new String[10]{}; is not allowed because new String[10]{ may be here 100 values};不允许,因为new String[10]{ may be here 100 values};

String array[]=new String[]; and String array[]=new String[]{};

No difference,these are just different ways of declaring array没有区别,这些只是声明数组的不同方式

String array=new String[10]{};字符串数组=新字符串[10]{}; got error why ?为什么出错?

This is because you can not declare the size of the array in this format.这是因为您不能以这种格式声明数组的大小。

right way is正确的方法是

String array[]=new String[]{"a","b"};

1.THE USE OF {}: 1.{} 的使用:

It initialize the array with the values { }它用值 { } 初始化数组

2.The difference between String array=new String[]; 2.String array=new String[]的区别; and String array=new String[]{};和字符串数组=新字符串[]{};

String array=new String[];字符串数组=新字符串[]; and String array=new String[]{};和字符串数组=新字符串[]{}; both are invalid statement in java.两者都是java中的无效语句。

It will gives you an error that you are trying to assign String array to String datatype.它会给您一个错误,提示您尝试将 String 数组分配给 String 数据类型。 More specifically error is like this Type mismatch: cannot convert from String[] to String更具体地说,错误是这样的 Type mismatch: cannot convert from String[] to String

3.String array=new String[10]{}; 3.字符串数组=新字符串[10]{}; got error why?有错误为什么?

Wrong because you are defining an array of length 10 ([10]), then defining an array of length String[10]错误,因为你定义了一个长度为 10 ([10]) 的数组,然后定义了一个长度为String[10]的数组{} 0 {} 0

Theory above is well explained.上面的理论解释得很好。

A PRACTICAL USE: Declare an array on the spot for a method parameter.实际使用:当场为方法参数声明一个数组。

MyResult result = myMethod(new String[]{"value1", "value2"});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 java 中的 String[]::new 和 new String[] 有区别吗? - Is there a difference between String[]::new and new String[] in java? Java中新String()和新String(“”)的字符串初始化有什么区别? - What is the difference between String initializations by new String() and new String(“”) in Java? 用new和“”初始化字符串之间的区别 - Difference between Initializing string with new and “ ” String.valueOf() 和 new String() 的区别 - Difference between String.valueOf() and new String() java的新手 - 新String()和weakHashMap之间的关系 - new to java - relationship between new String() and weakHashMap Long.valueOf(java.lang.String)和new Long(java.lang.String)之间的区别? - Difference between Long.valueOf(java.lang.String) and new Long(java.lang.String)? 新String(char [])和char []。toString之间的区别 - Difference between new String(char[]) and char[].toString “文本”和新字符串(“文本”)有什么区别? - What is the difference between "text" and new String("text")? 清单之间有区别吗 <String> A =新的ArrayList <String> ()和ArrayList <String> A =新的ArrayList <String> ()? - Is there a difference between List<String> A = new ArrayList<String> ( ) and ArrayList<String> A = new ArrayList<String>()? 字符串valueof(char [])和新字符串(char [])之间的区别 - difference between string valueof(char[]) and new string(char[])
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM