我知道应该用equals()方法来比较字符串是否相等。
我只是奇怪创建了两个字符串对象,为什么会应用同一个??

解决方案 »

  1.   

    String 是一个非常非常的类,
    我以前想到它的特殊性只想到它可以接受+,+=,而且也是唯一出现在Object源代码里的Object子类,现在又发现它应该是唯一一个不用new就可以得到实例的类。
    我估计,String str="xixi" 中"xixi"是常量,编译时与变量不同,类似C语言#define
      

  2.   

    String str2=new String("xixi"); returns false
      

  3.   

    是不是这么回事儿
    String str1 = "xixi";
    创建了一个字符串变量并初始化为"xixi"

    String str2 = "xixi";
    就将等价于
    String str2 = str1;
      

  4.   

    不是。
    In java, all variables are in either primitive type or object type.
      primitive type ex: int a;
      object type ex: Student stud;
    When we use '==' such as X == Y,
      primitive type: X and Y has the same value.
      object type: X and Y refers/points to the same Object.
    String is Object not pimitive, so '==' compares their addresses.
    For object type variables, one uses equalsTo to do the value level comparison. for user defined Classes, such as Student, Address, one has to implement equalsTo(..) method in order to compare.
      

  5.   

    你看一下String类下的equals()方法,你能看到
        public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = count;
        if (n == anotherString.count) {
    char v1[] = value;
    char v2[] = anotherString.value;
    int i = offset;
    int j = anotherString.offset;
    while (n-- != 0) {
        if (v1[i++] != v2[j++])
    return false;
    }
    return true;
        }
    }
    return false;
        }
    它是对两个字符串中的每个字符进行比较的
      

  6.   

    下面的代码可以说明问题:
    //teststring.javaclass teststring{
      public static void main(String[] args){
       String t=new String("111");
       String t1=new String("111");
       System.out.println((t==t1));
       System.out.println((t.equals(t1)));
       String s="111";
       String s1="111";
       System.out.println((s==s1));
       System.out.println((s.equals(s1)));
       Integer i=new Integer(2);
       Integer i1=new Integer(2);
       System.out.println((i==i1));
       System.out.println((i.equals(i1)));
       int j=2;
       int j1=2;
       System.out.println((j==j1));  
      }
    }
    F:\java>java  teststring
    false
    true
    true
    true
    false
    true
    true1、这说明楼主说的是事实
    2、String确实比较特殊,别的Object是不能直接赋值的。
       而他可以类似于int等数据类型进行赋值,我想处理方式也和int等相似。
       如 int t=1;int t1=1;t==t1肯定是true
       而String是Object,他当然用于Object的特性了。
      

  7.   

    摘自scjp 认证教材A String object is used to reference a string literal. All string literals in Java, such as “abc,” are implemented as instances of the String class. A string literal is basically a string of zero or more characters enclosed in double quotation s. Strings can store uppercase and lowercase letters, numbers, punctuation, and white space. All characters in String objects are stored in Unicode. Unicode is a two-byte character encoding system that includes thousands of international language symbols. Because of this, a string can hold text from writing systems used all over the world. However, programmers who are used to C or C++ will find that strings use twice as much memory. For example, the contents of the string “Hello, world.” will be 26 bytes long because it holds 13 two-byte characters. There is no limitation in Java on the potential length of a string, other than memory limitations.
     
     
     Creating a string can be deceptively simple. For example:
     
     
     String myName = “Pill Bug”;
     
     
     This constructor is reminiscent of a primitive constructor. Keep in mind that Strings are not primitives. They are objects, defined in the Java API in the java.lang package. They can also be constructed just like any other object. For example, the preceding code example is simply shorthand for the following: 
     
     
     String myName = new String(“Pill Bug”);
     
     
     Java programmers use methods within the String class to work with string variables. For example, there is a method in the string class named concat() that can be used to combine strings. The following code is an example of string concatenation.
     
     
     String a = “hello “;
    String b = “Pill Bug”;
    String c = a.concat(b); // c = “hello Pill Bug”
     
     
     Java provides shorthand for string concatenation by overloading the + (plus) operator. The following instructions have the same effect:
     
     
     String a = “hello ”;
    String b = “Pill Bug”;
    String c = a + b;
     
     
     It is important to be aware, however, that the + operator is merely a shortcut to other method calls, just as the double quotation s can be used as a shortcut to calling a string constructor directly.
     
      

  8.   

    If a string appears on either side of the + operator, the result is a String, and the Object.toString() method is called on any arguments that are not Strings. The certification test often has a code sample in which a number is concatenated to a String, so it is important to understand that this is allowed.
     
     
     Note that string concatenation is actually done using StringBuffer objects, not the concat() method of the String class.
     
     
     Despite a few shortcuts provided by the Java language, strings are objects, and the String class is just another class. Strings can be the arguments of methods or they can be returned by methods. They can be used in arrays or in other classes. All Java objects use the method toString() to return a String representation, including String objects. In other words, the String method toString() returns itself!
     
      

  9.   

    Storage of Strings and String Immutability 
     
     Many programmers with backgrounds in other languages are confused when they look at the methods of the String class. None of the methods defined actually change the referenced string object, they just return another string object. For instance, in the string concatenation example discussed earlier, the statement c = a.concat(b) doesn’t change either of the string variables a or b. It creates a new string, and assigns that string to c.
     
     
     It’s important to understand that in the Java programming language, once a string is created, it is immutable. Its contents can never be changed. There is no method that changes the contents of a string; there are only methods that take the source string as input and return another string. Strings in Java are not data structures that can be operated on; they can only be referenced.
     
     
     The reason for this is that a String object is not the string itself, it is just a reference to an in-memory location that contains a string of characters. The following source code provides an example of storage allocation for strings.
     
     
     String a = “hello”;
    String b = “hello”;
    String c = “hello”;
     
     
     To save space and reduce complexity, even though three strings are initialized, the Java compiler creates only a single memory space for storing the text hello, as shown in Figure 11-1. That memory space is shared by all three String objects, and the variables a, b, and c are simply pointers to that space.
     
    Figure11-1
     Variables sharing string objects at compile time
      
     
      
     
     
     Any changes to a single string would clearly affect all three. Therefore, by disallowing the direct manipulation of strings, the Java environment prevents changes in one string from impacting others.
     
     
     String references can, however, be reassigned. Consider the following example:
     
     
     String a = “hello”;
    String b = “hi”;
    String c = a;
    c = b;
     
     
     Two areas in memory are allocated for string storage. The first holds hello and the second holds hi, and the string variable c points to first one then the other, as shown in Figure 11-2.
     
    Figure11-2
     Variables point to immutable string objects
     
    Understanding string storage also explains some idiosyncrasies in string comparison in Java. Consider the following:
     
     
      1.  public class Test {
     2.     public static void main(String args[]) {
     3.        String a = “java”;
     4.        String b = “java”;
     5.        String x = “ja”;
     6.        String y = “va”;
     7.        String c = x + y;
     8.        if (a == b)
     9.           System.out.println(“a and b are the same object”);
    10.        else
    11.           System.out.println(“a and b are not the same object”);
    12.  
    13.        if (b == c)
    14.           System.out.println(“a and c are the same object”);
    15.        else
    16.           System.out.println(“a and c are not the same object”);
    17.     }
    18.  }
     
     
     When this Java source code is executed, the contents of the String variables a, b, and c will be the same: the string “java.” However, they will not all point to the same memory location, and thus the second comparison will fail. The output will look like this:
     
     
     a and b are the same object
    a and c are not the same object
     
     
     Even though the contents of a and c are the same, the word java, the string objects a and c do not point to the same memory location, so the comparison will fail. When the if statements are reached, the internal memory structures associated with these variables will look like Figure 11-3.
     
    The == operator is not the appropriate operator to use to determine the equality of string contents. Instead, the equals() method should be used. It is highly likely, however, that the certification exam will have questions regarding code samples similar to the preceding example to ensure you have an understanding of how strings are allocated. 
     
     
     programmers with a background in C may be concerned about needlessly creating strings. In a case where a string variable is reused over and over, the contents of many of the steps along the way may be lost. For example:
     
     
     String y = “yes”;
    String n = “no”;
    String m = “maybe”;
    String s = “I vote ” + y;
    String s = “I vote “ + n;
    String s = “I vote “ + m;
     
     
     In the preceding example, the strings “I vote yes”, “I vote no”, and “I vote maybe” are created at runtime. The memory contents then look like Figure 11-4.