Java toString method rewrite code example
•
Java
When you need to output an object to the display, you usually call his toString () method to convert the content of the object into a string All classes in java have a toString () method by default
By default, system out. Println (object name) or system out. Println (object name. Tostring()) outputs the class name of this object and the first memory address corresponding to this object. If you want to customize the output information, you must override the tostring() method
matters needing attention
1. Must be declared public
2. The return type is string
3. The name of the method must be toString without parameters
4. Do not use the output method system. In the method body out. println()
import java.util.*; public class TreeSetTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub SortedSet<Item> parts=new TreeSet<Item>(); parts.add(new Item("Toaster",1234)); parts.add(new Item("Widget",4562)); parts.add(new Item("Modem",9912)); System.out.println(parts); SortedSet<Item> sortByDescription=new TreeSet<Item>(new Comparator<Item>() { public int compare(Item a,Item b) { String descrA=a.getDescription(); String descrB=b.getDescription(); return descrA.compareTo(descrB); } }); sortByDescription.addAll(parts); System.out.println(sortByDescription); } } class Item implements Comparable<Item> { public Item(String aDescription,int aPartNumber) { description=aDescription; partNumber=aPartNumber; } public String getDescription() { return description; } public boolean equals(Object otherObject) { if(this==otherObject) return true; if(otherObject==null) { return false; } if (getClass()!=otherObject.getClass()) { return false; } Item other=(Item)otherObject; return description.equals(other.description)&& partNumber==other.partNumber; } public int hashCode() { return 13*description.hashCode()+17*partNumber; } public int compareTo(Item other) { return partNumber-other.partNumber; } private String description; private int partNumber; }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码