【问题标题】:How to use the toString method in Java?如何在 Java 中使用 toString 方法?
【发布时间】:2011-04-06 15:43:05
【问题描述】:

谁能向我解释toString() 方法的概念,在Object 类中定义?它是如何使用的,它的用途是什么?

【问题讨论】:

标签: java


【解决方案1】:

来自Object.toString 文档:

返回一个字符串表示 目的。一般来说,toString 方法返回一个字符串 “文字地表示”这个对象。 结果应该简洁但 信息表示是 一个人很容易阅读。它是 建议所有子类 覆盖此方法。

Object 类的 toString 方法 返回一个由 对象所属的类的名称 是一个实例,at-sign 字符 `@' 和无符号的十六进制 哈希码的表示 目的。换句话说,这种方法 返回一个等于该值的字符串 的:

getClass().getName() + '@' + Integer.toHexString(hashCode())

例子:

String[] mystr ={"a","b","c"};
System.out.println("mystr.toString: " + mystr.toString());

output:- mystr.toString: [Ljava.lang.String;@13aaa14a

【讨论】:

  • 主要目的是在子类中覆盖它。我认为@stephen 和 Andreas_D 的答案比公认的答案要好。
【解决方案2】:

使用String.toString

当您需要在 String 表单中探索名为 value 的构造函数时,您可以简单地使用 String.toString... 举个例子……

package pack1;

import java.util.*;

class Bank {

    String n;
    String add;
    int an;
    int bal;
    int dep;

    public Bank(String n, String add, int an, int bal) {

        this.add = add;
        this.bal = bal;
        this.an = an;
        this.n = n;

    }

    public String toString() {
        return "Name of the customer.:" + this.n + ",, "
                + "Address of the customer.:" + this.add + ",, " + "A/c no..:"
                + this.an + ",, " + "Balance in A/c..:" + this.bal;
    }
}

public class Demo2 {

    public static void main(String[] args) {

        List<Bank> l = new LinkedList<Bank>();

        Bank b1 = new Bank("naseem1", "Darbhanga,bihar", 123, 1000);
        Bank b2 = new Bank("naseem2", "patna,bihar", 124, 1500);
        Bank b3 = new Bank("naseem3", "madhubani,bihar", 125, 1600);
        Bank b4 = new Bank("naseem4", "samastipur,bihar", 126, 1700);
        Bank b5 = new Bank("naseem5", "muzafferpur,bihar", 127, 1800);
        l.add(b1);
        l.add(b2);
        l.add(b3);
        l.add(b4);
        l.add(b5);
        Iterator<Bank> i = l.iterator();
        while (i.hasNext()) {
            System.out.println(i.next());
        }
    }

}

...将该程序复制到您的Eclipse中,然后运行它...您将获得关于String.toString的想法...

【讨论】:

  • 我希望您知道 toString 不是有意的,也不适合 UI 用途。
  • @Powerslave 然后解释为什么所有 Swing 组件都使用toString 在 GUI 中显示一个对象?如果我有一个丰富的对象并且我想在 GUI 中显示它,那么不,我不会为它创建额外的渲染器,也不会从对象中提取字符串属性以在 GUI 中使用它,我保留它简单并实现toString 以规避所有开销。如果您想以更简洁的方式执行此操作,请创建一个专用于 UI 目的的包装器类,并实现其toString 方法以返回包装器的字符串属性。
  • @Timmos 如果您的朋友从桥上跳下,您会跟随吗?仅仅因为 Swing 开发人员使用(阅读;滥用)toString 函数并不意味着您也应该这样做。
  • 这是迄今为止完成工作最简单的方法,因为您继续使用默认的 Swing API。如果你想要自定义渲染,很好,在你的组件上安装一个自定义渲染器。如果您只想显示一个由字符串表示的对象,那么与自定义渲染器相比,实现 toString() 会容易得多,因为它有各种各样的陷阱来正确地做到这一点。我觉得你和跳桥的比较很奇怪。
【解决方案3】:

toString() 方法返回对象的文本 表示。 java.lang.Object 中已经包含了一个基本实现,因此因为所有对象都继承自 java.lang.Object,所以保证 Java 中的每个对象都有这个方法。

重写方法总是一个好主意,尤其是在调试时,因为调试器经常通过toString() 方法的结果显示对象。因此,请使用有意义的实现,但将其用于技术目的。应用程序逻辑应该使用 getter:

public class Contact {
  private String firstName;
  private String lastName;
  public Contact (String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  public String getFirstName() {return firstName;}
  public String getLastName() {return lastName;}

  public String getContact() {
    return firstName + " " + lastName;
  }

  @Override
  public String toString() {
    return "["+getContact()+"]";
  }
}

【讨论】:

    【解决方案4】:

    它可以选择性地在应用程序的上下文中使用,但更多时候它用于调试目的。例如,当您在 IDE 中遇到断点时,读取有意义的对象toString() 比检查其成员要容易得多。

    toString() 方法应该做什么没有固定要求。按照惯例,它通常会告诉您类的名称和相关数据成员的值。通常情况下,toString() 方法会在 IDE 中自动生成。

    依赖toString() 方法的特定输出或在程序中解析它是一个坏主意。无论你做什么,都不要走那条路。

    【讨论】:

    • 您能否详细说明您的最后陈述?
    【解决方案5】:

    toString() 返回对象的字符串/文本表示。 toString() 方法通常用于调试、日志记录等诊断目的,用于读取有关对象的有意义的详细信息。

    当对象传递给 println、print、printf、String.format()、assert 或字符串连接运算符时,会自动调用它。

    Object 类中 toString() 的默认实现返回一个字符串,该字符串由该对象的类名后跟@符号和该对象的哈希码的无符号十六进制表示,使用以下逻辑,

    getClass().getName() + "@" + Integer.toHexString(hashCode())
    

    例如下面的

    public final class Coordinates {
    
        private final double x;
        private final double y;
    
        public Coordinates(double x, double y) {
            this.x = x;
            this.y = y;
        }
    
        public static void main(String[] args) {
            Coordinates coordinates = new Coordinates(1, 2);
            System.out.println("Bourne's current location - " + coordinates);
        }
    }
    

    打印

    Bourne's current location - Coordinates@addbf1 //concise, but not really useful to the reader
    

    现在,在 Coordinates 类中覆盖 toString(),如下所示,

    @Override
    public String toString() {
        return "(" + x + ", " + y + ")";
    }
    

    结果

    Bourne's current location - (1.0, 2.0) //concise and informative
    

    当在包含对这些对象的引用的集合上调用该方法时,覆盖 toString() 的用处会变得更大。比如下面的

    public static void main(String[] args) {
        Coordinates bourneLocation = new Coordinates(90, 0);
        Coordinates bondLocation = new Coordinates(45, 90);
        Map<String, Coordinates> locations = new HashMap<String, Coordinates>();
        locations.put("Jason Bourne", bourneLocation);
        locations.put("James Bond", bondLocation);
        System.out.println(locations);
    }
    

    打印

    {James Bond=(45.0, 90.0), Jason Bourne=(90.0, 0.0)}
    

    而不是这个,

    {James Bond=Coordinates@addbf1, Jason Bourne=Coordinates@42e816}
    

    很少有实现指针,

    1. 您应该几乎总是覆盖 toString() 方法。 不需要覆盖的情况之一是实用程序类,它们以java.util.Math 的方式对静态实用程序方法进行分组。不需要覆盖的情况非常直观;几乎总是你会知道。
    2. 返回的字符串应该简洁明了,最好是一目了然。
    3. 至少,用于在两个不同对象之间建立等效性的字段,即在 equals() 方法实现中使用的字段应该由 toString() 方法吐出。
    4. 为返回的字符串中包含的所有实例字段提供访问器/获取器。例如,在坐标类中,

      public double getX() {
          return x;
      }
      public double getY() {
          return y;
      }
      

    toString() 方法的全面介绍参见 Josh Bloch 所著的 Effective Java™ 第二版一书的第 10 条。

    【讨论】:

      【解决方案6】:

      每当您在字符串上下文中访问对象(不是字符串)时,编译器都会在后台调用 toString()。

      这就是为什么

      Map map = new HashMap();
      System.out.println("map=" + map);
      

      有效,并且通过在您自己的类中从 Object 覆盖标准 toString(),您也可以使您的对象在 String 上下文中也有用。

      (并认为它是一个黑匣子!除了向人类展示之外,永远不要将内容用于其他任何事情)

      【讨论】:

        【解决方案7】:

        编码:

        public class Test {
        
            public static void main(String args[]) {
        
                ArrayList<Student> a = new ArrayList<Student>();
                a.add(new Student("Steve", 12, "Daniel"));
                a.add(new Student("Sachin", 10, "Tendulkar"));
        
                System.out.println(a);
        
                display(a);
        
            }
        
            static void display(ArrayList<Student> stu) {
        
                stu.add(new Student("Yuvi", 12, "Bhajji"));
        
                System.out.println(stu);
        
            }
        
        }
        

        Student.java:

        public class Student {
        
            public String name;
        
            public int id;
        
            public String email;
        
            Student() {
        
            }
        
            Student(String name, int id, String email) {
        
                this.name = name;
                this.id = id;
                this.email = email;
        
            }
        
             public String toString(){           //using these toString to avoid the output like this [com.steve.test.Student@6e1408, com.steve.test.Student@e53108]
                  return name+" "+id+" "+email;     
                 }  
        
        
            public String getName(){
        
                return name;
            }
        
            public void setName(String name){
        
                this.name=name;
            }
        
            public int getId(){
        
                return id;
            }
        
            public void setId(int id){
        
                this.id=id;
            }
        
            public String getEmail(){
        
                return email;
        
            }
        
            public void setEmail(String email){
        
                this.email=email;
            }
        }
        

        输出:

        [Steve 12 Daniel,Sachin 10 Tendulkar]

        [Steve 12 Daniel,Sachin 10 Tendulkar,Yuvi 12 Bhajji]

        如果你没有在 Pojo(Student.java) 类中使用 toString(),你会得到类似[com.steve.test.Student@6e1408, com.steve.test.Student@e53108]的输出。为了避免这类问题,我们使用了 toString() 方法。

        【讨论】:

          【解决方案8】:

          正确覆盖 toString 方法有助于 Java 的日志记录和调试。

          【讨论】:

            【解决方案9】:

            除了 cletus 对调试的回答之外,它在您输出对象时使用,例如在使用时

             System.out.println(myObject);
            

            System.out.println("text " + myObject);
            

            【讨论】:

              【解决方案10】:

              toString 的主要目的是生成一个对象的字符串表示,意味着返回值始终是一个字符串。在大多数情况下,这只是对象的类和包名,但在某些情况下,例如 StringBuilder,您实际上会得到一个字符串文本。

              【讨论】:

                【解决方案11】:

                如果您先学习 Python,然后学习 Java。我认为它与 Python 中的 __str__() 方法的作用相同,它是 magic method__dict__()__init__() 一样,但要引用表示对象的字符串。

                【讨论】:

                  【解决方案12】:

                  toString() 将指定的对象转换为字符串值。

                  【讨论】:

                    【解决方案13】:
                    /**
                     * This toString-Method works for every Class, where you want to display all the fields and its values
                     */
                    public String toString() {
                    
                        StringBuffer sb = new StringBuffer();
                    
                        Field[] fields = getClass().getDeclaredFields(); //Get all fields incl. private ones
                    
                        for (Field field : fields){
                    
                            try {
                    
                                field.setAccessible(true);
                                String key=field.getName();
                                String value;
                    
                                try{
                                    value = (String) field.get(this);
                                } catch (ClassCastException e){
                                    value="";
                                }
                    
                                sb.append(key).append(": ").append(value).append("\n");
                    
                            } catch (IllegalArgumentException e) {
                                e.printStackTrace();
                            } catch (SecurityException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                    
                        }
                    
                        return sb.toString();
                    }
                    

                    【讨论】:

                      猜你喜欢
                      • 2017-08-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2022-12-03
                      • 1970-01-01
                      • 1970-01-01
                      • 2015-12-05
                      相关资源
                      最近更新 更多