A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© adamjy 中级黑马   /  2014-4-3 01:47  /  992 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 adamjy 于 2014-4-5 20:07 编辑
  1. public class Test {
  2.         
  3.         public static void main(String[] args) {
  4.                 char[] aa = {'a','b','c'};
  5.                 System.out.println(aa.toString());
  6.         }
  7. }
复制代码


为什么程序输出是“[C@32e0c07c”乱码。另外,char数组有什么高效的转为字符串的方法吗?

评分

参与人数 1技术分 +1 收起 理由
菜小徐 + 1

查看全部评分

5 个回复

倒序浏览
aa.toString();方法打印出来的不是乱码,是内存地址。
因为java里面的所有类默认的继承Object,所以这里调用的是Object的toString()方法。
如果你看了源码就明白为什么这么打印了:
public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
这里还调用了Integer类中的方法:
public static String toHexString(int i) {
        return toUnsignedString(i, 4);
    }

private static String toUnsignedString(int i, int shift) {
        char[] buf = new char[32];
        int charPos = 32;
        int radix = 1 << shift;
        int mask = radix - 1;
        do {
            buf[--charPos] = digits[i & mask];
            i >>>= shift;
        } while (i != 0);

        return new String(buf, charPos, (32 - charPos));
    }

评分

参与人数 1技术分 +1 收起 理由
菜小徐 + 1

查看全部评分

回复 使用道具 举报
new String(char[])
回复 使用道具 举报
可以试试这个  System.out.println(Arrays.toString(aa));
回复 使用道具 举报
两点提醒,希望能帮到你,看代码。
  1. public static void main(String[] args) throws IOException{
  2.                 char[] aa = {'a','b','c'};
  3.                 //1.aa.toString()返回的是该数组的内存地址符
  4.                 System.out.println(aa.toString());
  5.                 //2.最好是用下面方法转换
  6.         System.out.println(new String(aa));
  7.         }
复制代码
回复 使用道具 举报
为什么程序输出是“[C@32e0c07c”乱码。另外,char数组有什么高效的转为字符串的方法吗?

那个是哈希值  第一个  [    符号 代表的是数组类型的引用
                    第二个  C   符号 代表数组是char 类型的 ,如果数组里放的是数字  这个 打印的就是I了(int)。
                    @后面的就是数组引用的地址值,aa里面存放的是引用地址值而不是数组内容。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马