String 类的一点认识

[size=small]
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));
}
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

annan211

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值