Tostringbuilder Learning (1): Common Methods

Source: Internet
Author: User

I. Introduction
1, tostringbuilder, hashcodebuilder, equalsbuilder, tostringstyle, reflectiontostringbuilder, comparetobuilder and so on these classes are located in the commons-lang.jar, so to use these classes must import commons-lang.jar.
2. Why use tostringbuilder?

Generally, logs must be printed in the system, because the tostring () method of all entities uses a simple "+", because every "+" method creates a new String object, in this way, if the system memory is small, the memory will be violent (the premise is that there are many system entities ). Using tostringbuilder can avoid the problem of violent memory.

Ii. Example Learning
1. append method of tostringbuilder

The tostringbuilder class is mainly used for formatting and output of classes. In tostringbuilder, The append method can add basic types, arrays, and objects to the class. Only the added method can be output by tostring. For example, class taxreturn {private string SSN; private int year; private string lastname; private bigdecimal taxableincome; // The get/Set Method omitting public taxreturn () {} public taxreturn (string pssn, int pyear, string plastname, bigdecimal ptaxableincome) {setssn (pssn); setyear (pyear); setlastname (plastname); settaxableincome (ptaxableincome);} Public String tostring () {return New tostringbuilder (this ). append ("SSN", SSN ). append ("year", year ). append ("lastname", lastname ). tostring ();} public int hashcode () {return New hashcodebuilder (3, 7 ). append (SSN ). append (year ). tohashcode ();} public Boolean equals (Object pobject) {Boolean equals = false; If (pobject instanceof taxreturn) {taxreturn bean = (taxreturn) pobject; equals = (New equalsbuilder (). append (SSN, Bean. SSN ). append (year, Bean. year )). isequals () ;}return equals;} public int compareto (Object pobject) {return comparetobuilder. reflectioncompare (this, pobject) ;}} public class mainclass {public static void main (string [] pargs) throws exception {taxreturn return1 = new taxreturn ("012-68-3242 ", 1998, "O 'Brien", new bigdecimal (43000.00); taxreturn return2 = new taxreturn ("012-68-3242", 1999, "O 'Brien ", new bigdecimal (45000.00); taxreturn return3 = new taxreturn ("012-68-3242", 1999, "O 'Brien", new bigdecimal (53222.00); system. out. println ("tostringbuilder:" + return1.tostring ());}}

The running result is as follows:
Tostringbuilder: [email protected] [SSN = 012-68-3242, year = 1998, lastname = O 'Brien]

2. reflectiontostring method of tostringbuilder

This method outputs the basic attributes and values corresponding to the class. For example:

Public class mainclass {

public static void main(String[] args) {    MyClass one = new MyClass("Becker", 35);    MyClass two = new MyClass("Becker", 35);    MyClass three = new MyClass("Agassi", 33);    System.out.println("One>>>" + one);    System.out.println("Two>>>" + two);    System.out.println("Three>>>" + three);    System.out.println("one equals two? " + one.equals(two));    System.out.println("one equals three? " + one.equals(three));    System.out.println("One HashCode>>> " + one.hashCode());    System.out.println("Two HashCode>>> " + two.hashCode());    System.out.println("Three HashCode>>> " + three.hashCode());}

}

Class myclass {

private String name = null;private int age = 0;public MyClass(String name, int age) {    this.name = name;    this.age = age;}public boolean equals(Object obj) {    return EqualsBuilder.reflectionEquals(this, obj);}public String toString() {    return ToStringBuilder.reflectionToString(this,        ToStringStyle.MULTI_LINE_STYLE);}public int hashCode() {    return HashCodeBuilder.reflectionHashCode(this);}

}
The running result is as follows:

One»> [email protected] [
Name = Becker
Age = 35
]
Two»> [email protected] [
Name = Becker
Age = 35
]
Three»> [email protected] [
Name = Agassi
Age = 33
]
One equals two? True
One equals three? False
One hashcode >> 462213092
Two hashcode >> 462213092
Three hashcode»>-530629296

Tostringstyle parameter description:

  1. Default_style
    [Email protected] [name = John Doe, age = 33, smoker = false]
  2. Multi_line_style
    [Email protected] [
    Name = john doe
    Age = 33
    Smoker = false
    ]
  3. No_field_names_style
    [Email protected] [John Doe, 33, false]
  4. Short_prefix_style (capture the package name)
    Person [name = John Doe, age = 33, smoker = false]
  5. Simple_style
    John Doe, 33, false

Additional:

No matter which Java application you are developing, you will inevitably need to write many tool classes/tool functions. You know, there are a lot of ready-made tool classes available, and the code quality is very good, you don't need to write, you don't need to debug, as long as you find out.

In Apache Jakarta common, the Lang Java toolkit is the most widely used among all Apache Jakarta common projects. It is useful in almost the well-known software you know, including tomcat, WebLogic, websphere, and eclipse. We will start from this package to introduce the entire common project.

There are many tool classes in Lang. Here we will introduce several main types:
Classutils: getjavasclassname. This function should be available in the Java. Lang. Class class. I see many people write this function by themselves. Getallinterfaces, convertclassnamestoclasses, isassignable, primitivestowrappers, and isinnerclass.
Numberutils: numeric and string conversion classes such as stringtoint, todouble, createnumber, isallzeros, int compare (float LHS, float RHs), isnumber (string Str ), double min (double [] array ).
Randomutils: used to generate random numbers.
Dateformatutils: converts the datetime format and the local time and UTC time.
Dateutils: Date tool class. Issameday, truncate, round, modify.

Reflection-based classes:
Comparetobuilder: comparison, used in algorithms, sorting, and comparison. Reflectioncompare, append.
Equalsbuilder: Comparison by reflection mechanism. Reflectionequals is used in many projects.
Hashcodebuilder: You can generate hash code through reflection. Many algorithms involve hash code, but not everyone knows how to generate hash code.
Tostringbuilder: this function can be used when you need to reload the tostring function without writing code to list all the member information of the current class.

I use less of the other classes:
Serialization in serializationutils Java is mysterious and error-prone.
Systemutils can be used to read JDK information and operating system information.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.