日期:2014-05-20  浏览次数:20624 次

print()的 问题
public class Test 

  public static void main(String[] args) 
  { 
  String str = "world"; 
  char[] ch = {'H','e','l','l','o'}; 
  change(str,ch); 
  System.out.print(str + "and "); 
  System.out.println(ch); 
  } 

  public static void change(String str,char[] ch) 
  { 
  str = "Change"; 
  ch[0] = 'C'; 
  } 


输出应该为 world and Cello 没有错 

可是我将输出合为一句的时候,也就是System.out.println(str + " and " + ch) 
输出为 world and [C@14318bb 

为什么我将输出合并为一句之后输出的ch就是一个好像是地址呢! 


------解决方案--------------------
char[] ch = {'H','e','l','l','o'}; //这是一个数组,print的 时候会调用其toString方法,会打印出
类名字@hashCode十六进制
------解决方案--------------------
用Arrays.toString.
------解决方案--------------------
char[] ch;
System.out.print(ch)

System.out.println(str+"and"+ch)
中print方法的实现是不一样的
print(ch)直接打印字符数组
print(str+"and"+ch)中按字符串打印,实现的是print(str+"and"+ch.toString())
ch指向的就是地址,直接将地址转化成字符串了
------解决方案--------------------
http://topic.csdn.net/u/20080521/21/eb2c08f7-8209-4c02-8215-6915afbc5d03.html
------解决方案--------------------
String类重写了object的toString()方法,就是打印String类型的字面值。
但是一个char[]是一个数组,pringf的时候调用的是object类的toString()方法,Object的toString()
方法默认就是打印hashcode的16进制数
------解决方案--------------------
看下面的解释

java.lang 
类 Object
java.lang.Object



toString
public String toString()返回该对象的字符串表示。通常,toString 方法会返回一个“以文本方式表示”此对象的字符串。结果应是一个简明但易于读懂的信息表达式。建议所有子类都重写此方法。 
Object 类的 toString 方法返回一个字符串,该字符串由类名(对象是该类的一个实例)、at 标记符“@”和此对象哈希码的无符号十六进制表示组成。换句话说,该方法返回一个字符串,它的值等于: 

getClass().getName() + '@' + Integer.toHexString(hashCode())
 
返回:
该对象的字符串表示形式。

------解决方案--------------------
(1)jdk 1.5帮助文档是这样写的(类PrintStream)
void print(char[] s) 
Print an array of characters. 

(2)print(str+"and"+ch)中按字符串打印,实现的是print(str+"and"+ch.toString()) 
ch指向的就是地址,直接将地址转化成字符串了,值如下:
getClass().getName() + '@' + Integer.toHexString(hashCode())