在引号内定义的字符数组?

时间:2012-11-04 05:25:35

标签: java string

我从这里得到了这个示例代码:

http://www.tutorialspoint.com/java/java_string_copyvalueof.htm

public class Test{
   public static void main(String args[]){
      char[] Str1 = "This is really not immutable!!";
      String Str2;

      Str2 = copyValueOf( Str1 );
      System.out.println("Returned String " + Str2);

      Str2 = copyValueOf( Str1, 5, 10 );
      System.out.println("Returned String " + Str2);

   }
}

此代码对我不起作用。

  1. 字符数组定义为字符串。
  2. copyValueOf无法识别!
  3. 现在我将其更改为:

        char[] Str1 = {'t','o','o','k'};
          String Str2;
    
          Str2 = copyValueOf( Str1 );
          System.out.println("Returned String " + Str2);
    
          Str2 = copyValueOf( Str1, 5, 10 );
          System.out.println("Returned String " + Str2);
    

    还是copyValueOf无效吗? 我检查了这个方法,它存在于文档中!

3 个答案:

答案 0 :(得分:4)

  1. 与C不同,char[]不是String,反之亦然。
  2. 您需要指定类:

    Str2 = String.copyValueOf( Str1 );
    

答案 1 :(得分:3)

您可能错过了代码中的static import。将其添加到文件顶部:

import static java.lang.String.copyValueOf;

或者,您可以(and perhaps should)明确指定该类。由于copyValueOf is a static member of String看起来像这样:

String.copyValueOf(Str1);

答案 2 :(得分:0)

以下是问题: