Javase Study Summary 13th day _API Common Objects 3

Source: Internet
Author: User

An overview of 13.01 StringBuffer

StringBuffer class overview: Variable character sequences for thread safety. A string-like buffer, but cannot be modified. Although it contains a specific sequence of characters at any point in time, some method calls can change the length and content of the sequence.

StringBuffer and string differences: StringBuffer length and content are variable, string is immutable. Concatenation of strings using stringbuffer does not waste too much resources

Construction method of 13.02 StringBuffer class

1. Public StringBuffer ():

Constructs a string buffer with no characters, with an initial capacity of 16 characters

2. Public stringbuffer (int capacity):

Constructs a string buffer with no characters, but with the specified initial capacity

3. Public StringBuffer (String str):

Constructs a string buffer and initializes its contents to the specified string content. The initial capacity of the string is 16 plus the length of the string parameter

Cases:

1 StringBuffer sb1 = new StringBuffer (), 2 System.out.println (Sb1.capacity ()),//163 System.out.println (Sb1.length ()); /04 5 StringBuffer SB2 = new StringBuffer ("Hello"); 6 System.out.println (Sb2.capacity ());//217 System.out.println ( Sb2.length ());//5

13.03 StringBuffer Add-on features

1. Public StringBuffer append (String str):

Appends the specified string to this sequence of characters

2. Public stringbuffer Insert (int offset,string str):

Inserts a string into this sequence of characters

13.04 StringBuffer removal function

1. Public stringbuffer deletecharat (int index):

Removes the char at the specified position of this sequence. This sequence will shorten a char

2. Public stringbuffer Delete (int start,int end):

Removes the characters in the substring of this sequence. The substring starts at the specified start, up to the character at index End-1, and, if no such character exists, until the end of the sequence. If start equals end, no change occurs

13.05 StringBuffer Replacement function

Public stringbuffer replace (int start,int end,string str):

Replaces a character in a substring of this sequence with a character in a given string

13.06 StringBuffer reversal function

Public StringBuffer reverse (): Replaces this sequence of characters with its inverted form

interception function of 13.07 StringBuffer

1. Public String substring (int start)

Returns a new String containing the sequence of characters currently contained in this character sequence

2. Public String substring (int start,int end)

Returns a new String that contains the sequence of characters that this sequence currently contains. The substring starts at the specified start and continues to the character at index End-1

13.08 StringBuffer and String conversions

Mutual conversion of string and StringBuffer

    • String→stringbuffer

STIRNG s;

1.StringBuffer sb = new StringBuffer (s);

2.StringBuffer sb = new StringBuffer (); Sb.append (s);

    • Stringbuffer→string

1.String s = new String (SB);

2.String s = sb.tostring ();

13.09 stitching Arrays into string cases in a specified format

1 public class Practice  2 {3 public     static void Main (string[] args)  4     {5         //definition array 6         int[] arr = {2 3,52,12,63,25}; 7         string s = arrtostring (arr); 8         System.out.println (s); 9     }10 public     static String arrtostring (int[] ARR)     {         StringBuffer sb = new StringBuffer ("["); "         (int i = 0; i < arr.length; i++)             (if (i = = arr.length-1) +             {                 sb.append (Arr[i]),             }19             else20             {21                 sb.append (Arr[i]). Append (",");         }24         sb.append ("]");         return sb.tostring ();     }27}

13.10 String inversion feature case

1 Import Java.util.Scanner; 2  3 public class practice  4 {5 public     static void Main (string[] args)  6     {7         Scanner sc = new Scan NER (system.in); 8         System.out.println ("Please enter data:"); 9         String str = Sc.nextline (); ten         string s = Myreverse (str);         System.out.println (s);     }13     public static string Myreverse (string s)         . {New StringBuffer (s). Reverse (). toString ();     }17 }

13.11 Judging whether a string is symmetrical case

Determines whether a string is a symmetric string, the example "ABC" is not a symmetric string, "ABA", "ABBA", "AAA", "MNANM" is a symmetric string

1 public class Practice  2 {3 public     static void Main (string[] args)  4     {5         String s = "ABCBA"; 6         S Ystem.out.println (IsSame2 (s)); 7     } 8//     Mode 1 9 public     static string Issame (String s) ten     {one          ///String to character array          char[] CHS = S.tocha Rarray (); (          int start = 0, end = chs.length-1; start <= end; start++, end--) (              Chs[start ]! = Chs[end]) ("Asymmetric                  "),              }19          }20          return "symmetric",     }22     //Mode 223     public static Boolean isSame2 (String s),     {         return new StringBuffer (s). Reverse (). ToString (). Equals (s); 26     }27}

Two questions of 13.12 StringBuffer

Question 1th: The difference between string,stringbuffer,stringbuilder

1.String is content immutable, and StringBuffer and StringBuilder are content-changeable

2.StringBuffer is synchronous, data security, low efficiency

StringBuilder is out of sync, data is unsafe, high efficiency

Question 2nd: StringBuffer and Array differences

StringBuffer and arrays are containers in which data can be loaded

StringBuffer can store any type of data, but eventually it is a string of data

Arrays can only store data of the same data type

13.13 string and StringBuffer are passed as arguments respectively

Cases:

1 public class Practice  2 {3 public     static void Main (string[] args)  4     {5         String s1 = "Hello"; 6         String s2 = "World"; 7         System.out.println (S1 + "---" + s2), 8 change         (S1, S2), 9         System.out.println (S1 + "---" + s2);         Strin Gbuffer sb1 = new StringBuffer ("Hello"),         stringbuffer SB2 = new StringBuffer ("World");         System.out.println (SB1 + "---" + sb2), change         (SB1, SB2),         System.out.println (SB1 + "---" + sb2);     Public     static void change (StringBuffer sb1, StringBuffer sb2),     {sb1         = sb2;20         sb2.append (sb1 );     }22 public     static void change (string s1, string s2):     {         S1 = s2;26         s2 = s1 + s2;27
   }28}

Operation Result:

Hello---worldhello---worldhello---worldhello---worldworld

Note: string is passed as a parameter, and the effect is passed as a parameter to the base type

13.14 Array Advanced bubble sort schematic diagram

Bubble sorting principle: The array 0 subscript number and 1 subscript number comparison, if 1 subscript number is less than 0 subscript the number of the exchange position, and then 1 subscript number and 2 subscript number comparison, if 1 subscript number is greater than 2 subscript number of the exchange position, and vice versa does not exchange position, Until the end of the comparison, the last subscript holds the largest number in the array, and the first round is the end of the comparison. And then from the 0 subscript and 1 subscript The number of comparison, at this time the last number does not need to participate in the comparison, repeat the above steps until the end. (sort from small to large)

13.15 Array Advanced bubble Sort code implementation

 1 public class Practice 2 {3/** 4 * Bubble sort 5 * @param args 6 */7 public static void Main (string[ ] args) 8 {9 int[] arr = {2,1,55,-12,45,25,-64};10 System.out.println ("before sorting:"); print (arr); Bubblesort (arr); System.out.println ("After sorting:"); print (arr);}16 public static void B Ubblesort (int[] arr) (int i = 0; i < arr.length-1; i++) 19 {20//-1 is to avoid a corner mark crossing 2                 1//-i is to allow the number of times the internal loop to participate in the comparison decreases as the outer loop increases (int j = 0, J < Arr.length-1-i; J + +) 23 {24 if (arr[j]>arr[j+1]) + {+ int temp = arr[j];27 A RR[J] = arr[j+1];28 arr[j+1] = temp;29}30}31}32}33//             Traversal array public static void print (int[] arr) (int i = 0; i < arr.length; i++) 37 {38 System.out.priNT (arr[i]+ "");}40 System.out.println (); 41}42} 

Operation Result:

13.16 Array advanced selection sorting schematic diagram

Select the sorting principle: the array of 0 subscript elements in order to compare with the following elements, if the element after 1 subscript is less than 0 subscript element will be the element and 0 subscript of the element exchange position, the comparison completes after 0 subscript element is stored is the minimum value, the first round is the end of the comparison. And then from the 1 subscript began to compare with the following elements, the comparison completed 1 subscript is the second small number, and so on until the end of the sort. (from small to large sort)

13.17 Array Advanced selection sort code implementation

 1 public class Practice 2 {3/** 4 * Select Sort 5 * @param args 6 */7 public static void Main (string[ ] args) 8 {9 int[] arr = {2,15,23,12,76,73,18,29};10 System.out.println ("before sorting:"); Print (arr  ); Selectsort (arr); System.out.println ("Sorted:"); print (arr);}16 public static void  Selectsort (int[] arr) (int i = 0; i < arr.length-1; i++) (Int j = i+1; J < Arr.length; J + +) (+) (arr[i]>arr[j) (+) (+) (+) (+) + temp = arr[i];2         5 Arr[i] = arr[j];26 Arr[j] = temp;27}28}29  }30}31//traversal array public static void print (int[] arr) (int i = 0; i < arr.length; i++) System.out.print (arr[i]+ "),}38 System.out.println (); 39}40}

Operation Result:

Before sorting: 2 15 23 12 76 73 18 29 Sorted: 2 12 15 18 23 29 73 76

13.18 sorting characters in a string case

1 public class Practice  2 {3     /** 4      * @param args 5      */6 public     static void Main (string[] args)  7< c10/>{8         String s = "DACGEBF"; 9         char[] ch = s.tochararray ();         selectsort (CH);         System.out.println (New String (CH));     }13 public     static void Selectsort (char[] ch)         int i = 0; i < ch.length-1; i++)             (int j = i+1, J < Ch.length, J + +), {+                 if (Ch[i] > Ch[j])                     temp = ch[i];22                     ch[i] = ch[j];23                     ch[j] = temp;24                 }25}26}27     }28}

13.19 An array of advanced binary search principle plots

Prerequisites for binary lookup array elements must be ordered

13.20 Array Advanced binary lookup code implementation

1 public class Practice  2 {3     /** 4      * binary find 5      * @param args 6 *      /7 public     static void Main (string[] args)  8     {9         int[] arr = {11,15,23,28,35,39,48,49,58};10         int index = BinarySearch (arr.);         SYSTEM.OUT.PRINTLN (index),     }13 public     static int BinarySearch (int[] arr,int key):     {         int min = 0;16         int max = arr.length-1;17         int mid = (Min+max)/2;18 while         (Arr[mid]!=key)             (arr[) Mid]>key)                 max = mid-1;22             if (arr[mid]<key)                 min = mid+1;24             if (Min>max)                 return-1;26             mid = (Min+max)/2;27         }28         return mid;29     }30}

13.21 binary find precautions to use

If the array element is unordered, the lookup in this case cannot use a binary lookup, because the binary lookup element must be ordered, and if it is sorted and then used for binary lookup, the original element index has been changed.

Overview and use of the 13.22 Arrays tool class

This class contains various methods for manipulating arrays, such as sorting and searching. This class also contains a static factory that allows the array to be viewed as a list.

Member Methods:

1. public static String toString (int[] a):

Returns a string representation of the contents of the specified array.

2. public static void sort (int[] a):

Sorts the specified array of type int in ascending order of numbers.

3. public static int BinarySearch (int[] a,int key):

Use the binary search method to search for the specified array of type int to get the specified value.

Cases:

1//define an array of 2 int[] arr = {23,25,65,85,34,82};3//array to string 4 System.out.println (arrays.tostring (arr)); 5//Array sort 6 arrays.sort ( ARR); 7 System.out.println (Arrays.tostring (arr)); 8//Two min find 9 System.out.println (Arrays.binarysearch (arr, 65));

Operation Result:

[23, 25, 65, 85, 34, 82] [23, 25, 34, 65, 82, 85]3

BinarySearch method If the number you are looking for exists in the array, the position of the number in the array is returned

If not present, returns the position where the number is inserted in the array, which is a negative number that indicates that the number to find does not exist in the array

The insertion position is calculated by: for example, 7 is returned, and the position in the array where it should be inserted is 7-1=6

Source code Analysis of 13.23 Arrays tool class

13.24 introduction of basic type wrapper class

To facilitate manipulation of the basic data type values, encapsulate the base data type as an object, define properties and behaviors in the object, the class used to describe the object is called the basic data type Object wrapper class, and the benefit is that more functional methods can be defined in the object to manipulate the data. One of the most common operations: for converting between basic data types and strings.

The construction method of 13.25 Integer

Integer class overview: The integer class wraps the value of a primitive type int in an object

The class provides several methods for converting between int and String types, as well as some other constants and methods that are useful when working with int types

Construction Method:

public Integer (int value):

Constructs a newly assigned Integer object that represents the specified int value.

Public Integer (String s) throws NumberFormatException:

Constructs a newly assigned Integer object that represents the int value indicated by the String parameter.

Cases:

1 int i = 100;2 integer i1 = new Integer (i), 3 System.out.println ("Integer:" +i1), 4 5 String s = "n"; 6 Integer i2 = new in Teger (s); 7 System.out.println ("Integer:" +i2);

13.26 conversion between string and int types

Int→string

1. Use the concatenation of the string "" +number

2. How to use string.valueof (int number) (recommended)

3. Use Integer to bridge, int→integer→string

Integer i = new Integer (number);

String s = i.tostring ();

4. How to use integer.tostring (int number)

String→int

1. Use Integer to bridge, String→integer→int

Integer i = new Integer (s);

int II = I.intvalue ();

2. How to use Integer.parseint (String s) (recommended)

13.27 Integer in-binary conversion operation

1. Common Basic binary conversions

A. public static String tobinarystring (int i):

Returns a string representation of an integer parameter as a binary (radix 2) unsigned integer.

B. public static String tooctalstring (int i):

Returns a string representation of an integer parameter as a eight-based (radix 8) unsigned integer.

C. public static String tohexstring (int i):

Returns a string representation of an integer parameter as a 16-based (radix 16) unsigned integer.

2. Decimal to other binary

public static String toString (int i,int radix):

Returns the string representation of the first parameter that specifies the cardinality representation with the second argument. Radix range from 2~36

3. Other binary to Decimal

public static int parseint (String s,int radix) throws NumberFormatException

Resolves a string argument to a signed integer using the cardinality specified by the second argument.

New features of 13.28 JDK5 automatic crating and unpacking

Auto-Boxing: Converting a base type to a wrapper class type

Auto-unpacking: Converting wrapper class types to basic types

JDK1.5 simplifies the way you define it.

Integer x = new Integer (4), which can be written directly

Integer x = 4;//equivalent to integer x = integer.valueof (4); auto Boxing

x = x + 5;//equivalent to x = Integer.valueof (X.intvalue () + 5), automatic unpacking, automatic packing

Note: When used, Integer x = null; The code above will appear nullpointerexception.

13.29 Integer Direct assignment of Face question

1.Integer i = 1;i + = 1;

At compile time:

Integer i = 1; equals integer i = integer.valueof (1);

i + = 1; equivalent to i = integer.valueof (I.intvalue () + 1);

2. See Program Write results

Integer i1 = new Integer (127);

Integer i2 = new Integer (127);

System.out.println (I1 = = i2);//false

System.out.println (I1.equals (I2));//true

Integer i3 = new Integer (128);

Integer i4 = new Integer (128);

System.out.println (i3 = = i4);//false

System.out.println (I3.equals (I4));//true

Integer i5 = 127;

Integer I6 = 127;

SYSTEM.OUT.PRINTLN (i5 = = I6);//true

System.out.println (I5.equals (I6));//true

Integer i7 = 128;

Integer i8 = 128;

System.out.println (i7 = = i8);//false

System.out.println (I7.equals (i8));//true

Note: Integer data is directly assigned, if between 128 and 127, the data is fetched directly from the buffer pool.

By looking at the source code, we know that for data between 128 and 127, a data buffer pool is made, and if the data is within that range, no new space is created each time

An overview of 13.30 character

The Character class wraps the value of a base type char in an object. An object of type Character contains a single field of type Char.

In addition, the class provides several methods to determine the categories of characters (lowercase letters, numbers, and so on), and to convert characters from uppercase to lowercase, and vice versa.

Construction Method:

Public Character (char value):

Constructs a newly allocated Character object that represents the specified char value.

13.31 character common methods of interpretation

1. public static Boolean isuppercase (char ch):

Determines whether the specified character is uppercase.

2. public static Boolean islowercase (char ch):

Determines whether the specified character is a lowercase letter.

3. public static Boolean isdigit (char ch):

Determines whether the specified character is a number.

4. public static char touppercase (char ch):

Converts the character argument to uppercase using the case mapping information taken from the Unicodedata file.

5. public static char toLowerCase (char ch):

Converts the character argument to lowercase using the case mapping information taken from the Unicodedata file.

13.32 case of uppercase lowercase and number occurrences in a statistical string

public class Practice {    /**     * @param args     *    /public static void main (string[] args)     {        String s = " SDFGD32SDF65HFG3SF S3EDF  S ";        int big = 0,SAMLL = 0,number = 0;        char[] CHS = S.tochararray ();        for (int i = 0; i < chs.length; i++)         {            if (character.isuppercase (Chs[i]))                big++;            else if (Character.islowercase (Chs[i]))                samll++;            else if (Character.isdigit (Chs[i]))                number++;        }        SYSTEM.OUT.PRINTLN ("uppercase character" +big+ "one");        System.out.println ("lowercase character" +samll+ "a");        System.out.println ("Numeric character" +number+ "One");}    }

Javase Study Summary 13th day _API Common Objects 3

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.