当前位置: 移动技术网 > IT编程>开发语言>Java > java中的 toString()方法实例代码

java中的 toString()方法实例代码

2019年07月22日  | 移动技术网IT编程  | 我要评论
前言:       tostring()方法 相信大家都用到过,一般用于以字符串的形式返回对象的相关数据。   最近项

前言:

      tostring()方法 相信大家都用到过,一般用于以字符串的形式返回对象的相关数据。

  最近项目中需要对一个arraylist<arraylist<integer>> datas  形式的集合处理。

  处理要求把集合数据转换成字符串形式,格式为 :子集合1数据+"#"+子集合2数据+"#"+....+子集合n数据。

  举例: 集合数据 :[[1,2,3],[2,3,5]]  要求转成为 "[1,2,3]#[2,3,5]" 形式的字符串

  第一次是这样处理的:

 arraylist<arraylist<object>> a = new arraylist<>();  // 打造这样一个数据的集合 [[1,2],[2,3]] 要求 生成字符串 [1,2]#[2,3]
    for (int i = 0; i < 2; i++) { 
      arraylist<object> c = new arraylist<>();
      c.add(i+1);
      c.add(i+2);
      a.add(c);
      //打印单个子集合的字符串形式数据
      log.i("myinfo",c.tostring());
    }
    stringbuilder builder = new stringbuilder();
    builder.append(a.get(0).tostring()+"#"+a.get(1).tostring());
    //打印该集合的字符串形式数据
    log.i("myinfo",builder.tostring());

  然后看该处理下的log日志:

05-12 10:29:18.485 9565-9565/com.xxx.aaa i/myinfo: [1, 2]
05-12 10:29:18.485 9565-9565/com.xxx.aaa i/myinfo: [2, 3]
05-12 10:29:18.495 9565-9565/com.xxx.aaa i/myinfo: [1, 2]#[2, 3]

   我们会发现我们想要的是[1,2]#[2,3]形式的字符串,但是结果是[1, 2]#[2, 3]  ,在第二个值开始往后,前面都多了一个空格。

   接下来我们查看 集合下的.tostring()方法的源码:

   翻译一下官方解释:

   1、返回这个collection类(set和list的父类) 的字符串表现形式

       2、这个表现形式有一个规定的格式,被矩形括号"[]"包含

       3、里面的子元素被“, ”(逗号和空格)分割 (这是重点)

 /**
   * returns the string representation of this {@code collection}. the presentation
   * has a specific format. it is enclosed by square brackets ("[]"). elements
   * are separated by ', ' (comma and space).
   *
   * @return the string representation of this {@code collection}.
   */
  @override
  public string tostring() {
    if (isempty()) {
      return "[]";
    }
    stringbuilder buffer = new stringbuilder(size() * 16);
    buffer.append('[');
    iterator<?> it = iterator();
    while (it.hasnext()) {
      object next = it.next();
      if (next != this) {
        buffer.append(next);
      } else {
        buffer.append("(this collection)");
      }
      if (it.hasnext()) {
        buffer.append(", ");
      }
    }
    buffer.append(']');
    return buffer.tostring();
  }

  分析这个collection下的.tostring()方法源码,分为几个部分:

  1、判断集合是不是空(empty),即集合内有没有数据。如果是空值(没有数据)的话,直接返回字符串 "[]"

      2、如果集合不是空值,说明有数据

    ①、迭代取下一个子元素(object next = it.next()),如果这个子元素是集合本身,添加"(this collection)"到stringbuffer类的buffer对象中

    ②、如果这个子元素不是集合本身,添加到buffer对象中

    ③、如果这个子元素下面还有子元素,则添加", "到buffer对象中去,用于分割两个相邻子元素

  3、返回stringbuffer.tostring()字符串

  由此可见,返回[1, 2]#[2, 3]是官方正确的返回形式,那么对于这个问题,其实在改不了源码的情况下 给得到的字符串后面使用.replaceall(" ",""); 把字符串中的空格都去掉

  注意:源码中有一段代码:         

   if (next != this) {
        buffer.append(next);
      } else {
        buffer.append("(this collection)");
      }

  这里可能有些同学看不懂,这里举个例子,还是上面的那个,我们在子集合里面 添加代码 c.add(c); 将集合本身添加到集合中去,看看打印结果

arraylist<arraylist<object>> a = new arraylist<>();
    for (int i = 0; i < 2; i++) {
      arraylist<object> c = new arraylist<>();
      c.add(i+1);
      c.add(i+2);
      c.add(c);
      //打印单个子集合的字符串形式数据
      log.i("myinfo",c.tostring());
    }

看日志结果中红色部分,是不是看懂了,如果集合中的子元素是集合本身,就将"(this collection)" 添加到返回集合中

05-12 10:58:00.615 8424-8424/com.maiji.magkarepatient i/myinfo: [1, 2, (this collection)]
05-12 10:58:00.615 8424-8424/com.maiji.magkarepatient i/myinfo: [2, 3, (this collection)]  

  至此,上面这个问题解决了,下面我们看下其他类下的.tostring()源码。

一、object

/**
   * returns a string containing a concise, human-readable description of this
   * object. subclasses are encouraged to override this method and provide an
   * implementation that takes into account the object's type and data. the
   * default implementation is equivalent to the following expression:
   * <pre>
   *  getclass().getname() + '@' + integer.tohexstring(hashcode())</pre>
   * <p>see <a href="{@docroot}reference/java/lang/object.html#writing_tostring">writing a useful
   * {@code tostring} method</a>
   * if you intend implementing your own {@code tostring} method.
   *
   * @return a printable representation of this object.
   */
  public string tostring() {
    return getclass().getname() + '@' + integer.tohexstring(hashcode());
  }

  翻译一下官方解释:

  1、返回一个对于这个object 简明的、可读的 的字符串

  2、object类的子类被鼓励去重写这个方法来提供一个实现用于描述对象的类型和数据

  3、默认的执行形式和下面这个例子一致

getclass().getname() + '@' + integer.tohexstring(hashcode())</pre>

  综上:当你的一个类中没有重写.tostring()方法的时候就会执行根类object的这个.tostring()方法。

     返回形式:对象的类名+@+哈希值的16进制

getclass().getname()返回对象所属类的类名
hashcode()返回该对象的哈希值
integer.tohexstring(hashcode())将对象的哈希值用16进制表示

 举例:

object d = new object();
log.i("myinfo",d.tostring());

05-12 11:23:00.758 17406-17406/com.maiji.magkarepatient i/myinfo: java.lang.object@e23e786

二、string,stringbuilder,stringbuffer

  三个都是字符串的表现形式,但是有区别的

  ①、string.tostring()  , 直接返回本身

  /**
   * returns this string.
   */
  @override
  public string tostring() {
    return this;
  }

  ②、stringbuilder

   官方解释:以字符串的形式 返回这个builder对象的内容

/**
   * returns the contents of this builder.
   *
   * @return the string representation of the data in this builder.
   */
  @override
  public string tostring() {
    /* note: this method is required to workaround a compiler bug
     * in the ri javac (at least in 1.5.0_06) that will generate a
     * reference to the non-public abstractstringbuilder if we don't
     * override it here.
     */
    return super.tostring();
  }

  追溯到super.tostring()实现

 /**
   * returns the current string representation.
   *
   * @return a string containing the characters in this instance.
   */
  @override
  public string tostring() {
    if (count == 0) {
      return "";
    }
    return stringfactory.newstringfromchars(0, count, value);
  }

  ③、stringbuffer

@override
  public synchronized string tostring() {
    return super.tostring();
  }

  追溯到super.tostring()

/**
   * returns the current string representation.
   *
   * @return a string containing the characters in this instance.
   */
  @override
  public string tostring() {
    if (count == 0) {
      return "";
    }
    return stringfactory.newstringfromchars(0, count, value);
  }

  综上我们发现,stringbuffer和stringbuilder最终都调用了父级  “abstractstringbuilder” 中的tostring()方法

  但是他们本身的tostring()却有所不同,我们由此可以总结

  1、stringbuilder:线程非安全的

     stringbuffer:线程安全的

      2、stringbuilder 处理速度要比 stringbudiler 快的多

  3、单线程大量数据操作,用stringbuilder  ,因为 stringbuilder速度快 , 因为单线程所以不考虑安全性

      多线程大量数据操作,用stringbuffer   ,  因为stringbuffer安全

三、map

  先看源码:

  可以看到返回的形式是{key1=value1, key2=value2}

  注意   1、当map集合中没有数据的时候 返回{}

     2、每两个数据之前用", "分割,和collection一致,一个逗号、一个空格

       3、当键值是集合本身的时候,添加  (this map)

public string tostring() {
    iterator<entry<k,v>> i = entryset().iterator();
    if (! i.hasnext())
      return "{}";
    stringbuilder sb = new stringbuilder();
    sb.append('{');
    for (;;) {
      entry<k,v> e = i.next();
      k key = e.getkey();
      v value = e.getvalue();
      sb.append(key  == this ? "(this map)" : key);
      sb.append('=');
      sb.append(value == this ? "(this map)" : value);
      if (! i.hasnext())
        return sb.append('}').tostring();
      sb.append(',').append(' ');
    }
  }

  举例:    

 map<string,string> map = new hashmap<>();
    map.put("keya","valuea");
    map.put("keyb","valueb");
    map.put("keyc","valuec");
    log.i("myinfo",map.tostring());

打印结果:

05-12 11:41:30.898 4490-4490/com.maiji.magkarepatient i/myinfo: {keya=valuea, keyb=valueb, keyc=valuec}

以上所述是小编给大家介绍的java中的 tostring()方法实例代码,希望对大家有所帮助

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网