Java Learning Path (v): Common object manipulation

Source: Internet
Author: User

Object Objects
Let's start by introducing the API

API (Application programming Interface): Application Programming Interface

Java API

    • is the class that Java provides to us, these classes encapsulate the underlying implementation.
    • We don't need to care how these classes are implemented, just learn how these classes are used.

Ojbect is a super class, any class will inherit with the object class, you do not write, the parent class is object by default

An overview of Object
    • object is the root class of a class hierarchy
    • All classes inherit directly or indirectly from the object class.
    • How to construct the object class: Public object ()
    • The constructor of a subclass is accessed by default for the parameterless construction method of the parent class
The Hashcode method of object

    • Object has a method public int hashcode ()
    • method returns a hash code value, which, by default, is calculated based on the address of the object
    • Hashcode () for different objects are generally not the same, but the hashcode value of the same object is definitely the same
    • Note: Hashcode is not the actual address value of an object and can be understood as a logical address value
 Public classTest { Public Static voidMain (string[] args) {studenttest std1=NewStudenttest ("null", 11); Studenttest STD2=NewStudenttest ("null", 12); Studenttest std3=STD1; System.out.println ("STD1:" +Std1.hashcode ()); System.out.println ("STD2:" +Std2.hashcode ()); System.out.println ("STD3:" +Std3.hashcode ()); }        }classstudenttest{String name; intAge ;  PublicStudenttest (String name,intAge ) {         This. Name =name;  This. Age =Age ; }}

The GetClass method of object

    • Returns this object run-time class
    • You can get the full name of the real class of the object through a method in class

 PackageDay15_nullnull; Public classTest { Public Static voidMain (string[] args) {studenttest std1=NewStudenttest ("null", 11); Studenttest STD2=NewStudenttest ("null", 12); Studenttest std3=STD1;        System.out.println (Std1.getclass ());        System.out.println (Std2.getclass ());    System.out.println (Std3.getclass ()); }        }classstudenttest{String name; intAge ;  PublicStudenttest (String name,intAge ) {         This. Name =name;  This. Age =Age ; }}

The ToString method of the object class
    • The ToString method returns the string representation of this object
    • General equivalent: package name [email protected]+integer.tohexstring (D.hashcode ())
    • But when we print an object, we call the ToString method by default, which is equivalent to the __str__ in Python.
    • This method is one that we use to customize the string output

Suggested overriding the ToString method

The Equals method of the object class
    • Indicates whether the object is equal to other objects
    • By default, the reference (address) of the object is the same
    • Because the reference to the comparison object is meaningless, it is generally recommended to override this method
Add: = = differs from the Equals method
    • = = is a comparison cloud algorithm, that is, you can compare basic data types, or you can compare reference data types
      • The base data type compares the value, and the reference data type compares the address value
    • The Equals method is a method that can only compare data types
      • The default equals and = = Compare reference data types without any difference
      • But by customizing, we can do what we want to compare the results
Some introduction to the scanner class

Scanner is a simple text scanner that can use regular expressions to parse basic types and strings

Scanner Method of Construction:

Scanner (InputStream Source)

system.in Introduction

    • There is a static field under the System class
    • public static final InputStream in standard input stream, corresponding to keyboard entry

Member Methods for scanner:

More IMPORTANT:

Hasnext. Determine if there is a next entry, where ... can be int,double and so on, if you need to determine whether to include a string, you can omit ...

Next .... Get the next entry

Commonly used for:

    • public int nextint (); Gets a value of type int
    • Public String nextline (); Gets a string of type value, which is the string
    • Note: It is best to use the same
The string class describes how to construct a string:
    • Public String ()
    • public string (byte[] bytes) Converts a byte array to a string
    • public string (byte[] bytes,int index,int length) converts part of a byte array to a string
    • public string (char[] Value,int index,int count) converts part of a character array to a string
    • The public string (string original) Initializes a newly created string object that represents a sequence of characters that is the same as the argument; that is, the newly created string is a copy of the parameter string (there is no thought of a deep copy)
 Packageday15_nullnull_01; Public classnull_string { Public Static voidMain (string[] args) {String str1=NewString ();                System.out.println (STR1); byte[] bytes1 = {97,98,99}; String str2=NewString (bytes1);                System.out.println (STR2); byte[] Bytes2 = {97,98,99,100,101,102,103}; String STR3=NewString (bytes2,1,4);                System.out.println (STR3); Char[] Chr = {' A ', ' B ', ' C '}; String STR4=NewString (CHR);            System.out.println (STR4); }        }

Let's take a look at some questions.
// 1. Determine if S1 and S2 that are defined as string types are equal String S1 = "abc"= "abc"= = = s2); System.out.println (s1.equals (S2));
true true // A constant has only one copy in memory
Answer
// 2. The following sentence creates several objects in memory?  New String ("abc");
// a total of two objects were created // a constant pool and a heap area each have one
Answer
// 3. Determine if S1 and S2 that are defined as string types are equal New String ("abc"= "abc"= = s2); System.out.println (s1.equals (S2));
Not the same, one in the heap address area, one in the constant area
Answer
// 4. Determine if S1 and S2 that are defined as string types are equal String S1 = "a" + "B" + "C"= "abc"= = = s2); System.out.println (s1.equals (S2));
Java's constant optimization mechanism in fact, when editing the S1 is already "ABC"
Answer
// 5. Determine if S1 and S2 that are defined as string types are equal String S1 = "AB"= "abc"= s1 + "C"= = s2); System.out.println (s3.equals (S2));
= =  falsetrue
AnswerThe judging function of the string class
    • public boolean equals (Object anobject) to determine if the string is the same
    • public boolean equalsignorecase (string anotherstring) determines if the string is the same, ignoring the case
    • Public Boolean contains (Charsequence s) determines whether the string contains those characters
    • public boolean startsWith (string prefix) determines whether a string begins with what
    • public boolean endsWith (string suffix) determines whether the string ends with
    • public Boolean isEmpty () determines whether the string is an empty string
Get function of String class
    • int length (): Gets the length of the string
    • char charAt (int index): Gets the character at the specified index position
    • int indexOf (int ch): Gets the index of the specified character at the first occurrence of this string
    • int indexOf (String str): Returns the index at the first occurrence of the specified string in this string
    • int indexOf (int ch,int fromIndex): Returns the index at the first occurrence of the specified character after the specified position in this string
    • int indexOf (String str,int fromIndex): Returns the index at the first occurrence of the specified string after the specified position in this string
    • LastIndexOf () The last occurrence of the position
    • string substring (int start): Intercepts the string starting at the specified position, default to the end
    • String substring (int start,int end): Ends The Intercept word from the specified position to the specified position metalized
Conversion capabilities of the String class
    • Byte[] GetBytes () converts a string into a byte array
    • Char[] ToCharArray () converts a string into a character array
    • static string ValueOf (char[] CHS) converts a character array to a string
    • static string valueOf (int i) converts data of type int to string
    • Add: The valueof method of string can convert any type of data into a string
    • String toLowerCase () turns the string into lowercase
    • String toUpperCase () turns the string into uppercase
    • String concat (String str) stitching strings and only stitching strings.
Some other features of the String class
    • Public String replace (char Oldchar,char newchar) substitution character
    • public string replace (charsequence target,charsequence replacement) Replacement string
    • Stringtrim (); Space before and after removal
    • public int CompareTo (String anotherstring) comparison
    • public int comparetoignorecase (String str) comparison
Overview of the StringBuffer class

thread -safe variable-character sequence, a string-like buffer similar to that of string

StringBuffer internal implementation is a string array

The difference between string and StringBuffer:

    • String is an immutable sequence of characters
    • StringBuffer is a variable sequence of characters
    • StringBuffer thread safety, can be locked
The construction method of StringBuffer class
    • Public StringBuffer () constructs a string buffer with no characters, with an initial capacity of 16 characters
    • public stringbuffer (int capacity) constructs a string buffer with no characters, but with a specified initial capacity
    • Public StringBuffer (charsequence seq) constructs a string buffer that contains the same characters as the specified charsequence
    • Public StringBuffer (String str) constructs a string buffer and initializes its contents to the specified string content
Methods of StringBuffer
    • public int Capacity () returns the current capacity. (theoretical value?) )
    • The public int length () returns the length (number of characters) (actual value)
StringBuffer Add-on features
    • Public stringbuffer Append (String str) can add any type of data to the character buffer and return a character buffer itself
    • Public stringbuffer Insert (int offset,string str) inserts any type of data into the character buffer at the specified location and returns the string buffer itself
StringBuffer removal function
    • Public stringbuffer deletecharat (int index) deletes the character at the specified position and returns itself
    • Public StringBuffer Delete (int start,int end) Deletes the content starting at the specified position to the end of the specified position and returns itself
StringBuffer Replacement and rollover functions
    • Public stringbuffer replace (int start,int end,string str) is replaced with Str from start to end
    • Public StringBuffer reverse () Flip of string
Interception of StringBuffer
    • Public String substring (int start) intercepts from the specified position to the end
    • Public String substring (int start,int end) intercepts from the specified position to the end position, including the start position, not including the end position
    • Note: The previous return value is StringBuffer, this time returning a string
Conversion between string and StringBuffer

String===>stringbuffer

1. Through the construction method, when the StringBuffer is created, the string is passed as a parameter

2. Through the apped () method

Stringbuffer===>string

1. The same over-construction method

2. Via the ToString () method of the StringBuffer

3. Using substring (start,end) Slicing method

Add:

The difference between 1.StringBuffer and StringBuilder

    • StringBuffer is a jdk1.0 version, thread-safe, and inefficient.
    • StringBuilder is a jdk1.5 version and is thread insecure, but also highly efficient

The difference between 2.String and StringBuffer and StringBuilder

    • String is an immutable sequence of characters
    • StringBuffer and StringBuilder are a variable sequence of characters

Java Learning Path (v): Common object manipulation

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.