练习测试题:
Consider the following code:
String entree = new String (“chicken”);
String side = “salad”;
entree = “turkey”;
String dessert;
entree = side;
String extra = entree + side;
dessert = “pie”;
How many String objects were created, and how many are accessible at the end?
How many aliases are present, and is there any garbage?我的逻辑是:创建了3个文本,一个带有new运算符的字符串,以及一个连接entree和side的字符串,因此总共创建了5个对象。
甜点和额外的是2个对象,边和主菜的第三次分配。因此,在总共创建的5个对象中,有4个是可访问的。
1别名,entree指的是side。
垃圾,主菜丢失了对“火鸡”和“鸡肉”的引用。
你能帮我评估一下我对这个问题的思考过程吗?
发布于 2012-12-16 04:59:08
如果尚未创建这四个文字,则将创建它们。
当字符串包含char[]时,new String可能会创建一个或两个新对象
在卸载类之前,不会释放字符串文字。
当使用String +时,将创建一个StringBuilder、一个或两个char[]和一个String。
String extra = entree + side;可以翻译为
String extra = new StringBuilder().append(entree).append(side).toString();这意味着有一个新的StringBuilder/String和一个char[]。
这意味着最多有6个对象可以被垃圾回收。
https://stackoverflow.com/questions/13896068
复制相似问题