[size=small]
String 是Java中相当强大的类,虽不属于基本类型,但是非常重要。
关于Stirng 其他的不做过多介绍,这里简要说明几个小点。
[/size]
[size=small]
以上代码 表明,即使str3 新开辟了空间,其仍指向 和str1一样的实体,也就是说 str3创建新对象的时候,仍然使用的是 常量池当中的值。 intern 方法 作用是 首先进入常量池查看有无该常量,没有的话就创建并且把值放入常量池。
String 类当中 存在一个以空间换时间的方法 substring(index,index2)
使用不当会造成 内存溢出
代码 如下
[/size]
String 是Java中相当强大的类,虽不属于基本类型,但是非常重要。
关于Stirng 其他的不做过多介绍,这里简要说明几个小点。
[/size]
package String;
public class StringDemo {
public static void main(String[] args) {
String str1 = "abc";
String str2 = "abc";
String str3 = new String("abc");
System.out.println(str1==str2); //true
System.out.println(str1==str3); //false
System.out.println(str1==str3.intern()); //true
}
}
[size=small]
以上代码 表明,即使str3 新开辟了空间,其仍指向 和str1一样的实体,也就是说 str3创建新对象的时候,仍然使用的是 常量池当中的值。 intern 方法 作用是 首先进入常量池查看有无该常量,没有的话就创建并且把值放入常量池。
String 类当中 存在一个以空间换时间的方法 substring(index,index2)
使用不当会造成 内存溢出
代码 如下
[/size]
package String;
import java.util.ArrayList;
import java.util.List;
/**
* 其中导致内存溢出 是由其源码决定的,源码使用了 牺牲空间换取时间的做法
*
* public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
这段源码指出 ,即使只截取一小段,也会把原始字符串全部返回,肯定会撑爆。
* @author Administrator
*
*/
public class HugeStr {
public static void main(String[] args) {
List<String> hander = new ArrayList<String>();
for(int i=0;i<1000;i++){
// HugeStrD h = new HugeStrD();// 这个方法会导致 内存溢出
InvohandleHugeStrD h = new InvohandleHugeStrD();//这个不会内存溢出
hander.add(h.getSubString(1, 5));
}
}
static class HugeStrD{
private String str = new String (new char[10000000]);//很长的String
public String getSubString(int begin,int end){
return str.substring(begin, end);
}
}
static class InvohandleHugeStrD{
private String str = new String (new char[10000000]);//很长的String
public String getSubString(int begin,int end){
return new String(str.substring(begin, end));
}
}
}