String在JVM内存中的存储java
使用String str1 = "abc";方式建立的字符串存放在常量池中;数组
使用String str2 = new String("abc");方式建立的字符串存放在堆中;此方式更占内存;安全
String类的hashCode()方法,equals()方法多线程
hashcode()方法是Object类中的方法,默认返回JVM中的32位内存地址;String重写了hashCode()方法并发
public int hashCode() { int h = hash; //Default to 0 ### String类中的私有变量, if (h == 0 && value.length > 0) { //private final char value[]; ### Sting类中保存的字符串内容的的数组 char val[] = value; for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } hash = h; } return h; }
String的比较,==是运算符,比较的是引用变量自己,而不是引用变量指向的对象;app
equals()方法是Object中的方法,默认使用==比较;String类重写了equals()方法;工具
//一个字符串常量的引用使用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;//value属性获取字符数组 int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; }
String类是不可变类,任何对String的改变都 会引起新的String对象的生成,动态的构建String数据应该用StringBuffere类。性能
String类为何要设计成不可变:https://my.oschina.net/kailuncen/blog/1483860ui
线程安全:this
先说一下集合的故事,HashTable是线程安全的,不少方法都是synchronized方法,而HashMap不是线程安全的,但其在单线程程序中的性能比HashTable要高。StringBuffer和StringBuilder类的区别也是如此,他们的原理和操做基本相同,区别在于StringBufferd支持并发操做,线性安全的,适 合多线程中使用。StringBuilder不支持并发操做,线性不安全的,不适合多线程中使用。新引入的StringBuilder类不是线程安全的,但其在单线程中的性能比StringBuffer高。
经常使用字符串工具类
/* 对象转换为字符串,对象为null时转化为空字符串*/ public static String convertNullToEmpty(Object obj) { return obj == null ? "" : String.valueOf(obj); } /* 对象转换为字符串,避免"null"的出现*/ public static String objectToString(Object obj) { return obj == null ? null : obj + ""; } /* 判断字符串 是否 为数字*/ public static boolean isNumeric(String str) { Pattern pattern = Pattern.compile("[0-9]*"); Matcher isNum = pattern.matcher(str); if (!isNum.matches()) { return false; } return true; } public static boolean isEmpty(String str) { if (null == str || "null".equals(str) || "".equals(str)) return true; else { return false; } }