CharSequence类型
这是一个接口,代表的是一个有序字符集合,这个接口包含的方法有:charAt(int index),toString(),length(),subSequence(int start,int end).
这里需要说的一点就是,对于一个抽象类或者是接口类,不能使用new来进行赋值,但是可以通过以下的方式来进行实例的创建:
CharSequence cs="hello";
但是不能这样来创建:
CharSequence cs=new CharSequence("hello");
接下来看个测试类,
public class CharSequenceTest {
public static void main(String[] args) {
CharSequence obj = "hello";
String str = "hello";
System.out.println("Type of obj: " + obj.getClass().getSimpleName());
System.out.println("Type of str: " + str.getClass().getSimpleName());
System.out.println("Value of obj: " + obj);
System.out.println("Value of str: " + str);
System.out.println("Is obj a String? " + (obj instanceof String));
System.out.println("Is obj a CharSequence? " + (obj instanceof CharSequence));
System.out.println("Is str a String? " + (str instanceof String));
System.out.println("Is str a CharSequence? " + (str instanceof CharSequence));
System.out.println("Is \"hello\" a String? " + ("hello" instanceof String));
System.out.println("Is \"hello\" a CharSequence? " + ("hello" instanceof CharSequence));
System.out.println("str.equals(obj)? " + str.equals(obj));
System.out.println("(str == obj)? " + (str == obj));
}
}
控制台输出如下:
Type of obj: String
Type of str: String
Value of obj: hello
Value of str: hello
Is obj a String? true
Is obj a CharSequence? true
Is str a String? true
Is str a CharSequence? true
Is "hello" a String? true
Is "hello" a CharSequence? true
str.equals(obj)? true
(str == obj)? true
具体可参考:http://stackoverflow.com/questions/11323962/exact-difference-between-charsequence-and-string-in-java