String类 StringBuilder StringBuffer源码

tech2024-01-08  78

 String类被final修饰 实现了CharSequence的接口,有被final修饰的char型数组,因此是不可变的

public final class String implements java.io.Serializable, Comparable<String>, CharSequence { /** The value is used for character storage. */ private final char value[]; /** Cache the hash code for the string */ private int hash; // Default to 0 /** use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = -6849794470754667710L;

charAt()方法

public char charAt(int index) { if ((index < 0) || (index >= value.length)) { throw new StringIndexOutOfBoundsException(index); } return value[index]; }

 equals()方法

public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; }

 String类的hashcode计算方式

public int hashCode() { int h = hash; if (h == 0 && value.length > 0) { char val[] = value; for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } hash = h; } return h; }

StringBuilder 和StringBuffer都继承了AbstractStringBuilder,实现了CharSequence接口

区别是StringBuffer是线程安全的,原因是在append方法中用sychronized修饰,因此在效率方面,StringBuilder是高于StringBuffer的。如果我们使用不经常改变的字符串,使用String,如果单线程经常改变,使用StringBuilder,多线程下使用StringBuffer.

@Override public StringBuilder append(String str) { super.append(str); return this; }

 

@Override public synchronized StringBuffer append(String str) { toStringCache = null; super.append(str); return this; }

 

最新回复(0)