关于java常量存储方式的问题,大家帮忙看一下

stonewomen 2011-11-24 10:44:51
最近学习java,有个String的小问题请教一下大伙,大家帮忙看一下!
String str=new String("Hello");
System.out.prinln(str.length());//输出为5
本人查了一下String的源码,有如下几个构造方法:
public String(String original) {
int size = original.count;
char[] originalValue = original.value;
char[] v;
if (originalValue.length > size) {
// The array representing the String is bigger than the new
// String itself. Perhaps this constructor is being called
// in order to trim the baggage, so make a copy of the array.
int off = original.offset;
v = Arrays.copyOfRange(originalValue, off, off+size);
} else {
// The array representing the String is the same
// size as the String, so no point in making a copy.
v = originalValue;
}
this.offset = 0;
this.count = size;
this.value = v;
}


public String(char value[]) {
int size = value.length;
this.offset = 0;
this.count = size;
this.value = Arrays.copyOf(value, size);
}

public int length() {
return count;
}
对于str.length(),返回的是Count的值即字符串的长度,我想问的是对于new String("Hello")调用的是哪个构造方法,如果调用的是String(String original),那么在这个函数中Hello的长度是怎么来的,编译器如何解释这部分,大虾们帮忙看一下!!!
...全文
83 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
stonewomen 2011-11-24
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 chenjing0320 的回复:]
你在写“hello”的时候虚拟机自动创建了一个完整String对象,当然就有count的值。
我猜虚拟机是把“hello”拆成一个字符数组,调用字符数组的构造方法创建String对象。
[/Quote]
我也赞同这个算法,顶一下!!!
chenjing0320 2011-11-24
  • 打赏
  • 举报
回复
你在写“hello”的时候虚拟机自动创建了一个完整String对象,当然就有count的值。
我猜虚拟机是把“hello”拆成一个字符数组,调用字符数组的构造方法创建String对象。
stonewomen 2011-11-24
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 chenjing0320 的回复:]
调用的肯定是String(String original)
int size = original.count;
this.count = size;
这两句就是把长度赋值了啊
[/Quote]

那么Hello的Count值从哪来的呀?
chenjing0320 2011-11-24
  • 打赏
  • 举报
回复
“hello”本身就是一个字符串对象,它的count已经有值了。在String类内部可以直接访问私有变量。
chenjing0320 2011-11-24
  • 打赏
  • 举报
回复
调用的肯定是String(String original)
int size = original.count;
this.count = size;
这两句就是把长度赋值了啊

50,549

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧