Learning objectives
- Understand math related API s
- Understanding the datetime API
- Understand system class API
- Master the basic array algorithm
- Master the use of array tool class
- Proficient in String API
- Proficient in StringBuilder and StringBuffer API
- Can handle string related algorithms
1. Mathematics related classes
1.1 java.lang.Math
The java.lang.Math class contains methods for performing basic mathematical operations, such as elementary exponents, logarithms, square roots, and trigonometric functions. For a tool class like this, all its methods are static methods and will not create objects. It is very simple to call.
- public static double abs(double a): returns the absolute value of the double value.
double d1 = Math.abs(-5); //The value of d1 is 5 double d2 = Math.abs(5); //The value of d2 is 5
- public static double ceil(double a): returns the smallest integer greater than or equal to the parameter.
double d1 = Math.ceil(3.3); //The value of d1 is 4.0 double d2 = Math.ceil(-3.3); //The value of d2 is - 3.0 double d3 = Math.ceil(5.1); //The value of d3 is 6.0
- public static double floor(double a): returns an integer less than or equal to the maximum parameter.
double d1 = Math.floor(3.3); //The value of d1 is 3.0 double d2 = Math.floor(-3.3); //The value of d2 is - 4.0 double d3 = Math.floor(5.1); //The value of d3 is 5.0
- public static long round(double a): returns the long closest to the parameter. (equivalent to rounding method)
long d1 = Math.round(5.5); //The value of d1 is 6.0 long d2 = Math.round(5.4); //The value of d2 is 5.0
- public static double pow(double a,double b): returns the b-power method of A
- public static double sqrt(double a): returns the square root of A
- public static double random(): returns the random value of [0,1]
- public static final double PI: returns PI
- public static double max(double x, double y): returns the maximum value of x,y
- public static double min(double x, double y): returns the minimum value of x,y
double result = Math.pow(2,31); double sqrt = Math.sqrt(256); double rand = Math.random(); double pi = Math.PI;
practice
Please use Math related API s to calculate the number of integers with absolute values greater than 6 or less than 2.1 between - 10.8 and 5.9?
public class MathTest { public static void main(String[] args) { // Define minimum double min = -10.8; // Define maximum double max = 5.9; // Define variable count int count = 0; // Cycle in range for (double i = Math.ceil(min); i <= max; i++) { // Get absolute value and judge if (Math.abs(i) > 6 || Math.abs(i) < 2.1) { // count count++; } } System.out.println("The number is: " + count + " individual"); } }
1.2 java.math package
(1)BigInteger
An immutable integer of arbitrary precision.
- BigInteger(String val)
- BigInteger add(BigInteger val)
- BigInteger subtract(BigInteger val)
- BigInteger multiply(BigInteger val)
- BigInteger divide(BigInteger val)
- BigInteger remainder(BigInteger val)
- ...
@Test public void test01(){ // long bigNum = 123456789123456789123456789L; BigInteger b1 = new BigInteger("123456789123456789123456789"); BigInteger b2 = new BigInteger("78923456789123456789123456789"); // System.out.println("sum:" + (b1+b2)); / / error, cannot be summed directly with + System.out.println("And:" + b1.add(b2)); System.out.println("Minus:" + b1.subtract(b2)); System.out.println("Multiply:" + b1.multiply(b2)); System.out.println("Except:" + b2.divide(b1)); System.out.println("Yu:" + b2.remainder(b1)); }
(2) RoundingMode enumeration class
CEILING: rounding mode that rounds to positive infinity.
DOWN: rounding mode for rounding to zero.
FLOOR: the rounding mode of rounding to negative infinity.
HALF_DOWN: the rounding mode of rounding in the direction closest to the number. If the distance from two adjacent numbers is equal, it will be rounded down.
HALF_EVEN: the rounding mode of rounding in the direction closest to the number. If the distance from two adjacent numbers is equal, it will be rounded to the adjacent even number.
HALF_UP: the rounding mode of rounding in the direction closest to the number. If the distance from two adjacent numbers is equal, it will be rounded up.
UNNECESSARY: the rounding pattern used to assert that the requested operation has an exact result, so rounding is not required.
UP: rounding mode for rounding away from zero.
(3)BigDecimal
An immutable signed decimal number of arbitrary precision.
- BigDecimal(String val)
- BigDecimal add(BigDecimal val)
- BigDecimal subtract(BigDecimal val)
- BigDecimal multiply(BigDecimal val)
- BigDecimal divide(BigDecimal val)
- BigDecimal divide(BigDecimal divisor, int roundingMode)
- BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode)
- BigDecimal remainder(BigDecimal val)
- ...
@Test public void test02(){ /*double big = 12.123456789123456789123456789; System.out.println("big = " + big);*/ BigDecimal b1 = new BigDecimal("123.45678912345678912345678912345678"); BigDecimal b2 = new BigDecimal("7.8923456789123456789123456789998898888"); // System.out.println("sum:" + (b1+b2)); / / error, cannot be summed directly with + System.out.println("And:" + b1.add(b2)); System.out.println("Minus:" + b1.subtract(b2)); System.out.println("Multiply:" + b1.multiply(b2)); System.out.println("Except:" + b1.divide(b2,20,RoundingMode.UP));//divide(BigDecimal divisor, int scale, int roundingMode) System.out.println("Except:" + b1.divide(b2,20,RoundingMode.DOWN));//divide(BigDecimal divisor, int scale, int roundingMode) System.out.println("Yu:" + b1.remainder(b2)); }
1.3 java.util.Random
Used to generate random numbers
-
boolean nextBoolean(): returns the next pseudo-random number, which is a uniformly distributed boolean value from this random number generator sequence.
-
void nextBytes(byte[] bytes): generate random bytes and place them in the byte array provided by the user.
-
double nextDouble(): returns the next pseudo-random number, which is the double value evenly distributed between 0.0 and 1.0 from this random number generator sequence.
-
float nextFloat(): returns the next pseudo-random number, which is the float value evenly distributed between 0.0 and 1.0 from this random number generator sequence.
-
double nextGaussian(): returns the next pseudo-random number. It is the double value in Gaussian ("normal") distribution taken from the random number generator sequence. Its average value is 0.0 and its standard deviation is 1.0.
-
int nextInt(): returns the next pseudo-random number, which is the int value evenly distributed in the sequence of this random number generator.
-
int nextInt(int n): returns a pseudo-random number, which is an int value evenly distributed between 0 (inclusive) and the specified value (exclusive) from this random number generator sequence.
-
long nextLong(): returns the next pseudo-random number, which is a uniformly distributed long value taken from this random number generator sequence.
@Test public void test03(){ Random r = new Random(); System.out.println("Random integer:" + r.nextInt()); System.out.println("Random decimal:" + r.nextDouble()); System.out.println("Random Boolean:" + r.nextBoolean()); }
2. Date and time API
2.1 before JDK1.8
1,java.util.Date
new Date(): current system time
long getTime(): returns the millisecond value between 0.0.0 milliseconds from 1970-1-1 for the date time object
new Date(long millisecond): converts the millisecond value into a date time object
@Test public void test5(){ long time = Long.MAX_VALUE; Date d = new Date(time); System.out.println(d); } @Test public void test4(){ long time = 1559807047979L; Date d = new Date(time); System.out.println(d); } @Test public void test3(){ Date d = new Date(); long time = d.getTime(); System.out.println(time);//1559807047979 } @Test public void test2(){ long time = System.currentTimeMillis(); System.out.println(time);//1559806982971 //The time difference between the current system time and 1970-1-1 0:0:0 0 milliseconds, in milliseconds } @Test public void test1(){ Date d = new Date(); System.out.println(d); }
2,java.util.TimeZone
Usually, getDefault is used to obtain the TimeZone, and getDefault creates the TimeZone based on the time zone in which the program runs.
You can also use getTimeZone time zone ID to obtain TimeZone. For example, the time zone ID of the U.S. Pacific time zone is "America / los_angels".
@Test public void test8(){ String[] all = TimeZone.getAvailableIDs(); for (int i = 0; i < all.length; i++) { System.out.println(all[i]); } } @Test public void test7(){ TimeZone t = TimeZone.getTimeZone("America/Los_Angeles"); }
Common time zone ID:
Asia/Shanghai UTC America/New_York
3,java.util.Calendar
Calendar class is an abstract class, which is associated with a set of such as YEAR, MONTH, DAY_OF_MONTH, HOUR, etc. for a specific moment Calendar field The conversion between provides some methods and provides some methods for operating the Calendar field (for example, obtaining the date of the next week). The moment can be expressed in milliseconds, which is the distance from the epoch (i.e. 00:00.000 on January 1, 1970, Greenwich mean time, Gregorian Calendar) Like other locale sensitive classes, Calendar provides a class method getInstance to obtain a common object of this type.
(1) getInstance(): get the object of Calendar
(2) Get (constant)
@Test public void test6(){ Calendar c = Calendar.getInstance(); System.out.println(c); int year = c.get(Calendar.YEAR); System.out.println(year); int month = c.get(Calendar.MONTH)+1; System.out.println(month); //... } @Test public void test7(){ TimeZone t = TimeZone.getTimeZone("America/Los_Angeles"); //getInstance(TimeZone zone) Calendar c = Calendar.getInstance(t); System.out.println(c); }
4,java.text.SimpleDateFormat
SimpleDateFormat is used to format the date and time.
@Test public void test10() throws ParseException{ String str = "2019 Thursday, June 6, 2006 16:03:14.545 MS +0800"; SimpleDateFormat sf = new SimpleDateFormat("yyyy year MM month dd day HH Time mm branch ss second SSS millisecond E Z"); Date d = sf.parse(str); System.out.println(d); } @Test public void test9(){ Date d = new Date(); SimpleDateFormat sf = new SimpleDateFormat("yyyy year MM month dd day HH Time mm branch ss second SSS millisecond E Z"); //Convert the Date into a string and convert it in the specified format String str = sf.format(d); System.out.println(str); }
2.2 after JDK1.8
Java 1.0 includes a Date class, but most of its methods have been abandoned after the introduction of the calendar class in Java 1.1. Calendar is not much better than Date. The problems they face are:
- Variability: class objects such as date and time should be immutable. There are three methods in the Calendar class to change Calendar fields: set(), add(), and roll().
- Offset: the year in Date starts from 1900, and the month starts from 0.
- Formatting: formatting is only useful for Date, but not Calendar.
- In addition, they are not thread safe and cannot handle leap seconds and so on.
It can be said that the operation of date and time has always been one of the most painful places for Java programmers. The API introduced for the third time is successful, and the java.time API introduced in java 8 has corrected the defects in the past, and it will serve us for a long time in the future.
Java 8 absorbs the essence of Joda-Time and creates a good API for Java with a new start.
- java.time – base package containing value objects
- java.time.chrono – provides access to different calendar systems.
- java.time.format – format and parse time and date
- Java.time.temporary – includes the underlying framework and extension features
- java.time.zone – contains classes that support time zones
Java 8 absorbs the essence of Joda-Time and creates a good API for Java with a new start. The new java.time contains all classes about Clock, local date, local time, local datetime, ZonedDateTime, and Duration.
1. Local date and time: LocalDate, LocalTime, LocalDateTime
method | describe |
---|---|
now() / now(ZoneId zone) | Static method to create an object based on the current time / an object with a specified time zone |
of() | Static method to create an object based on a specified date / time |
getDayOfMonth()/getDayOfYear() | Days of acquisition month (1-31) / days of acquisition year (1-366) |
getDayOfWeek() | Gets the day of the week (returns a DayOfWeek enumeration value) |
getMonth() | Get the Month and return a Month enumeration value |
getMonthValue() / getYear() | Acquisition month (1-12) / acquisition year |
getHours()/getMinute()/getSecond() | Obtain the hour, minute and second corresponding to the current object |
withDayOfMonth()/withDayOfYear()/withMonth()/withYear() | Modify the month days, year days, month and year to the specified value and return a new object |
with(TemporalAdjuster t) | Sets the current date and time to the date and time specified by the proofreader |
plusDays(), plusWeeks(), plusMonths(), plusYears(),plusHours() | Add days, weeks, months, years, hours to the current object |
minusMonths() / minusWeeks()/minusDays()/minusYears()/minusHours() | Subtract months, weeks, days, years, hours from the current object |
plus(TemporalAmount t)/minus(TemporalAmount t) | Add or remove a Duration or Period |
isBefore()/isAfter() | Compare two localdates |
isLeapYear() | Determine whether it is a leap year (declared in the LocalDate class) |
format(DateTimeFormatter t) | Format the local date and time, and return a string |
parse(Charsequence text) | Parses the string in the specified format into date and time |
@Test public void test7(){ LocalDate now = LocalDate.now(); LocalDate before = now.minusDays(100); System.out.println(before);//2019-02-26 } @Test public void test06(){ LocalDate lai = LocalDate.of(2019, 5, 13); LocalDate go = lai.plusDays(160); System.out.println(go);//2019-10-20 } @Test public void test05(){ LocalDate lai = LocalDate.of(2019, 5, 13); System.out.println(lai.getDayOfYear()); } @Test public void test04(){ LocalDate lai = LocalDate.of(2019, 5, 13); System.out.println(lai); } @Test public void test03(){ LocalDateTime now = LocalDateTime.now(); System.out.println(now); } @Test public void test02(){ LocalTime now = LocalTime.now(); System.out.println(now); } @Test public void test01(){ LocalDate now = LocalDate.now(); System.out.println(now); }
2. Specify time zone date time: ZonedDateTime
Common time zone ID:
Asia/Shanghai UTC America/New_York
import java.time.ZoneId; import java.time.ZonedDateTime; public class TestZonedDateTime { public static void main(String[] args) { ZonedDateTime t = ZonedDateTime.now(); System.out.println(t); ZonedDateTime t1 = ZonedDateTime.now(ZoneId.of("America/New_York")); System.out.println(t1); } }
3. Duration: Period and duration
Period: used to calculate the interval between two dates
public static void main(String[] args) { LocalDate t1 = LocalDate.now(); LocalDate t2 = LocalDate.of(2018, 12, 31); Period between = Period.between(t1, t2); System.out.println(between); System.out.println("Years of difference:"+between.getYears());//1 year System.out.println("Months of difference:"+between.getMonths());//Another seven months System.out.println("Days difference:"+between.getDays());//Zero 25 days System.out.println("Total number of differences:"+between.toTotalMonths());//19 months in total }
Duration: used to calculate two time intervals
public static void main(String[] args) { LocalDateTime t1 = LocalDateTime.now(); LocalDateTime t2 = LocalDateTime.of(2017, 8, 29, 0, 0, 0, 0); Duration between = Duration.between(t1, t2); System.out.println(between); System.out.println("Total days of difference:"+between.toDays()); System.out.println("Total hours of difference:"+between.toHours()); System.out.println("Total minutes of difference:"+between.toMinutes()); System.out.println("Total seconds of difference:"+between.getSeconds()); System.out.println("Total milliseconds of difference:"+between.toMillis()); System.out.println("Total nanoseconds of phase difference:"+between.toNanos()); System.out.println("Nanoseconds less than one second:"+between.getNano()); }
4. DateTimeFormatter: date time formatting
This class provides three formatting methods:
Predefined standard formats. E.g. ISO_DATE_TIME;ISO_DATE
Localization related formats. For example: ofLocalizedDate(FormatStyle.MEDIUM)
Custom format. For example: ofPattern("yyyy MM DD HH: mm: SS")
@Test public void test10(){ LocalDateTime now = LocalDateTime.now(); // DateTimeFormatter df = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);// June 6, 2019 04:40:03 PM DateTimeFormatter df = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);//19-6-6 4:40 pm String str = df.format(now); System.out.println(str); } @Test public void test9(){ LocalDateTime now = LocalDateTime.now(); DateTimeFormatter df = DateTimeFormatter.ISO_DATE_TIME;//2019-06-06T16:38:23.756 String str = df.format(now); System.out.println(str); } @Test public void test8(){ LocalDateTime now = LocalDateTime.now(); DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy year MM month dd day HH Time mm branch ss second SSS millisecond E It's this year D day"); String str = df.format(now); System.out.println(str); }
3. System related
3.1 java.lang.System class
There are many useful methods in the system class, several of which are as follows:
-
static long currentTimeMillis(): returns the millisecond value of the current system time distance 1970-1-1 0:0:0
-
static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length):
Copies an array from the specified source array, starting at the specified location and ending at the specified location of the target array. It is often used to insert and delete arrays
-
static void exit(int status): exit the current system
-
static void gc(): run the garbage collector.
-
static String getProperty(String key): get a system property
-
...
public class Test{ public static void main(String[] args){ long time = System.currentTimeMillis(); System.out.println("The current system time is from the early morning of January 1, 1970:" + time + "millisecond"); System.exit(0); System.out.println("over");//Will not execute } }
3.3 java.lang.Runtime class
Each Java application has a Runtime class instance that enables the application to connect to its running environment. You can get the current Runtime through the getRuntime method. The application cannot create its own instance of the Runtime class.
public static Runtime getRuntime(): returns the runtime object related to the current Java application.
public long totalMemory(): returns the total memory in the Java virtual machine. The value returned by this method may vary over time, depending on the host environment.
public long freeMemory(): returns the amount of free memory in the Java virtual machine. Calling the gc method may cause the return value of freeMemory to increase.
4 algorithm sublimation of array
4.1 algorithm sublimation of array
1. Inversion of arrays
There are two methods:
1. With a new array
2. Head and tail corresponding position exchange
Example code of the first method:
int[] arr = {1,2,3,4,5,6,7,8,9}; //(1) Create a new array first int[] newArr = new int[arr.length]; //(2) Copy element int len = arr.length; for(int i=0; i<newArr.length; i++){ newArr[i] = arr[len -1 - i]; } //(3) Discard the old and let arr point to the new array arr = newArr;//Here, the first address of the new array is assigned to arr //(4) Traversal display for(int i=0; i<arr.length; i++){ System.out.println(arr[i]); }
Disadvantages: you need to use an array to waste additional space, and the original array needs garbage collection
Example code of the second method:
**Implementation idea: * * elements in the symmetrical position of the array are exchanged.
int[] arr = {1,2,3,4,5,6,7,8,9}; //(1) Calculate the number of times to exchange: number = arr.length/2 //(2) Head tail symmetrical position exchange for(int i=0; i<arr.length/2; i++){//The number of cycles is the number of exchanges int temp = arr[i]; arr[i] = arr[arr.length-1-i]; arr[arr.length-1-i] = temp; } //(3) Traversal display for(int i=0; i<arr.length; i++){ System.out.println(arr[i]); }
or
public static void main(String[] args){ int[] arr = {1,2,3,4,5,6,7,8,9}; //Left right symmetrical position exchange for(int left=0,right=arr.length-1; left<right; left++,right--){ //Head and tail exchange int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //(3) Traversal display for(int i=0; i<arr.length; i++){ System.out.println(arr[i]); } }
2. Expansion of array
Example: when the original array is not long enough, it needs to be expanded. For example, it needs to add a new location to store 10
int[] arr = {1,2,3,4,5,6,7,8,9}; //If you want to expand the arr array, add 1 position //(1) First create a new array. Its length = the length of the old array + 1, or it can be expanded to 1.5 times or 2 times the length of the original array int[] newArr = new int[arr.length + 1]; //(2) Copy element //Note: I < arr.length because bit arr is shorter than newArr, avoid subscript out of bounds for(int i=0; i<arr.length; i++){ newArr[i] = arr[i]; } //(3) Add the new element to the end of newArr newArr[newArr.length-1] = 10; //(4) If you continue to use arr below, you can make arr point to the new array arr = newArr; //(4) Traversal display for(int i=0; i<arr.length; i++){ System.out.println(arr[i]); }
(1) As for the appropriate length definition of the new array, it depends on the actual situation. If the number of new elements is determined, the specified length can be increased. If the number of new elements is uncertain, the capacity can be expanded to 1.5 times or 2 times the original
(2) Too much array expansion will cause waste, too little will lead to frequent expansion and low efficiency
3. Insertion of array elements
Example: insert an element in a [index] of the original array
Case 1: the original array is not full
String[] arr = new String[5]; arr[0]="Zhang San"; arr[1]="Li Si"; arr[2]="Wang Wu"; At present, the length of the array is 5, and the actual number of elements of the array is 3. If you need to insert a "Zhao Liu" between "Zhang San" and "Li Si", that is[index=1]Insert "Zhao Liu" in the position of. What should I do?
String[] arr = new String[5]; arr[0]="Zhang San"; arr[1]="Li Si"; arr[2]="Wang Wu"; //(1) Move 2 elements. The subscript of the starting element to be moved is [1]. It needs to be moved to [2]. There are 2 elements in total System.arraycopy(arr,1,arr,2,2); //(2) Insert new element arr[1]="Zhao Liu"; //(3) Traversal display for(int i=0; i<arr.length; i++){ System.out.println(arr[i]); }
Scenario 2: the original array is full
String[] arr = new String[3]; arr[0]="Zhang San"; arr[1]="Li Si"; arr[2]="Wang Wu"; At present, the length of the array is 3, and the actual number of elements of the array is 3. If you need to insert a "Zhao Liu" between "Zhang San" and "Li Si", that is[index=1]Insert "Zhao Liu" in the position of. What should I do?
String[] arr = new String[3]; arr[0]="Zhang San"; arr[1]="Li Si"; arr[2]="Wang Wu"; //(1) Capacity expansion first String[] newArr = new String[4]; for(int i=0; i<arr.length; i++){ newArr[i] = arr[i]; } arr=newArr; //(2) Move 2 elements. The subscript of the starting element to be moved is [1]. It needs to be moved to [2]. There are 2 elements in total System.arraycopy(arr,1,arr,2,2); //(3) Insert new element arr[1]="Zhao Liu"; //(4) Traversal display for(int i=0; i<arr.length; i++){ System.out.println(arr[i]); }
4. Deletion of array elements
Example:
String[] arr = new String[3]; arr[0]="Zhang San"; arr[1]="Li Si"; arr[2]="Wang Wu"; Now we need to delete "Li Si". We don't want empty elements in the middle of the array. What should we do?
String[] arr = new String[3]; arr[0]="Zhang San"; arr[1]="Li Si"; arr[2]="Wang Wu"; //(1) To move an element, you need to move the starting subscript [2] of the element. The element needs to be moved to [1]. A total of 1 element needs to be moved System.arraycopy(arr,2,arr,1,1); //(2) Because the array elements move to the left as a whole, this is essentially a copy. The original last element needs to be empty arr[2]=null;//Enables garbage collection to reclaim the memory of the corresponding object as soon as possible
5. Binary search of array
Binary search: half fold, half fold, and then half fold
Requirement: the array elements must support comparison size, and the elements in the array have been sorted by size
Example:
class Exam2{ public static void main(String[] args){ int[] arr = {2,5,7,8,10,15,18,20,22,25,28};//Arrays are ordered int value = 18; int index = -1; int left = 0; int right = arr.length - 1; int mid = (left + right)/2; while(left<=right){ //Find end if(value == arr[mid]){ index = mid; break; }//Can't find else if(value > arr[mid]){//Continue to find to the right //Move the left boundary so that the mid moves to the right left = mid + 1; }else if(value < arr[mid]){//Continue to the left right = mid - 1; } mid = (left + right)/2; } if(index==-1){ System.out.println(value + "non-existent"); }else{ System.out.println(value + "The subscript is" + index); } } }
6. Direct selection sorting of arrays
Example code: simple direct selection sorting
int[] arr = {49,38,65,97,76,13,27,49}; for(int i=1; i<arr.length; i++){//Number of outer loops = number of rounds = length of array - 1 //(1) Find the latest value in the unordered elements in this round /* Unsorted elements: Round 1: i=1, unordered, [0,7], the first element of unordered elements in this round is [0] Round 2: i=2, unordered, [1,7]. The first element of unordered elements in this round is [1] ... Round 7: i=7, unordered, [6,7], the first element of unordered elements in this round is [6] The starting subscript of each round of unordered elements: 0,1,2,3,4,5,6, which is exactly the starting subscript of i-1 The following elements that are not sorted are: Round 1: [1,7] J = 1,2,3,4,5,6,7 Round 2: [2,4] J = 2,3,4,5,6,7 . . . . Round 7: [7] J = 7 j The starting point is i and the ending point is 7 */ int max = arr[i-1]; int index = i-1; for(int j=i; j<arr.length; j++){ if(arr[j] > max){ max = arr[j]; index = j; } } //(2) If the maximum value is not in the position it should be, it is exchanged with the element in this position /* Round 1, the maximum value should be [0] In the second round, the maximum value should be [1] .... Round 7, the maximum value should be [6] Exactly the value of i-1 */ if(index != i-1){ //Exchange arr[i-1] and arr[index] int temp = arr[i-1]; arr[i-1] = arr[index]; arr[index] = temp; } } //Display results for(int i=0; i<arr.length; i++){ System.out.print(arr[i]); }
4.2 array tool class
The java.util.Arrays array tool class provides many static methods to operate arrays, and each of the following methods has various overloaded forms. Only arrays of type int [] are listed below, and so on:
-
static int binarySearch(int[] a, int key): the array is required to be ordered. Check whether the key exists in the array. If it exists, return the index found for the first time, and if not, return a negative number
-
static int[] copyOf(int[] original, int newLength): copy a new array with a length of newLength according to the original array of original, and return the new array
-
static int[] copyOfRange(int[] original, int from, int to): copy [from, to] of the original array to form a new array and return the new array
-
static boolean equals(int[] a, int[] a2): compare whether the length and elements of two arrays are identical
-
static void fill(int[] a, int val): fill the entire a array with val
-
static void fill(int[] a, int fromIndex, int toIndex, int val): fill the part of a array [fromIndex,toIndex) with val
-
static void sort(int[] a): sort the a array from small to large
-
static void sort(int[] a, int fromIndex, int toIndex): sort the [fromIndex, toIndex) part of the a array in ascending order
-
static String toString(int[] a): splice the elements of array a into a string in the form of: [element 1, element 2, element 3...]
Example code:
import java.util.Arrays; import java.util.Random; public class Test{ public static void main(String[] args){ int[] arr = new int[5]; // Print the array and output the address value System.out.println(arr); // [I@2ac1fdc4 // Convert array contents to strings System.out.println("arr Array initial state:"+ Arrays.toString(arr)); Arrays.fill(arr, 3); System.out.println("arr Array current state:"+ Arrays.toString(arr)); Random rand = new Random(); for (int i = 0; i < arr.length; i++) { arr[i] = rand.nextInt(100);//Assigned to a random integer within 100 } System.out.println("arr Array current state:"+ Arrays.toString(arr)); int[] arr2 = Arrays.copyOf(arr, 10); System.out.println("New array:" + Arrays.toString(arr2)); System.out.println("Comparison results of two arrays:" + Arrays.equals(arr, arr2)); Arrays.sort(arr); System.out.println("arr Array current state:"+ Arrays.toString(arr)); } }
4.3 interview questions
1. Programming question 1
Find a value in the array so that the sum of the left value is equal to the sum of the right value,
For example: [1,2,5,3,2,4,2], the result is: the fourth value is 3
[9, 6, 8, 8, 7, 6, 9, 5, 2, 5], the result is No
public static void main(String[] args) { int[] arr = {1,2,5,3,2,4,2}; int index = leftSumEqualsRightSum(arr); if(index!=-1) { System.out.println(arr[index]); }else { System.out.println("No,"); } } public static int leftSumEqualsRightSum(int[] arr) { for (int mid = 0; mid < arr.length; mid++) { int leftSum = 0; int rightSum = 0; for (int i = 0; i <mid; i++) { leftSum += arr[i]; } for (int i = mid+1; i < arr.length; i++) { rightSum += arr[i]; } if(leftSum==rightSum) { return mid; } } return -1; }
2. Programming question 2
-
Left odd right even
- An array of 10 integers {26,67,49,38,52,66,7,71,56,87}.
- Elements are rearranged, all odd numbers are saved to the left of the array, and all even numbers are saved to the right of the array.
-
Code implementation, and the effect is shown in the figure:
-
Development tips:
- The even number on the left and the odd number on the right change positions:
- Define two variables, left and right. Start from the left to find the positions of even numbers. After finding them, use left to record them. Start from the right to find the positions of odd numbers. After finding them, use right to record them. If left < right, exchange them, and then continue to search on the basis of the previous time until left and right rub shoulders.
//Highest efficiency public void order2(int[] arr){ for (int left = 0,right = arr.length-1; left < right; ){ //Left represents the subscript of the number to be exchanged on the left, and the subscript of the even number //If arr[left] is an odd number at this time, it means that left is not the subscript we are looking for, and left + + moves back while(arr[left]%2!=0){//When arr[left] is an even number, end the while loop left++; } //If arr[right] is an even number at this time, it means that right is not the subscript we are looking for. Right -- move forward while(arr[right]%2==0){//When arr[right] is an odd number, end the while loop right--; } if(left < right){ int temp = arr[left]; arr[left] = arr[right]; arr[right]= temp; } } }
public void order3(int[] arr){ int len = arr.length; while (len>0) { for (int j=0; j<len-1; j++){ //The element on the left is even and is exchanged with its adjacent elements if (arr[j]%2==0) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } len--; } }
public void order(int[] arr){ //Find an even number from left to right, and record the subscript, evenIndex, which is the subscript of the wrong number //Find the odd number from the right to the left, and record the subscript, oddIndex, which is the subscript of the wrong number //Exchange arr[oddIndex] and arr[evenIndex] and adjust them int evenIndex = 0; int oddIndex = arr.length-1; while(evenIndex < oddIndex){ for (int i=0; i<arr.length; i++){ if(arr[i]%2==0){ evenIndex = i; break; } } for(int i=arr.length-1; i>=0; i--){ if(arr[i]%2!=0){ oddIndex = i; break; } } if(evenIndex < oddIndex) { int temp = arr[evenIndex]; arr[evenIndex] = arr[oddIndex]; arr[oddIndex] = temp; } } }
3. Programming question 3
-
Array de duplication
- 10 integers {9,10,6,6,1,9,3,5,6,4}, with a range of 1-10, are saved in the array.
- Remove duplicates in the array and keep only unique elements.
-
Write the code step by step, and the effect is shown in the figure:
-
Development tips:
- Define a variable count, which is initialized to the length of the array
- Traverse each element. If the element is equal to a previous element, move the array, overwrite the element, and modify count –.
- Finally, create a new array with the length of count, and copy the first count elements from the original array
4. Programming question 4
import java.util.Arrays; public class TestExer4 { public static void main(String[] args) { double[] arr = new double[10]; for (int i = 0; i < arr.length-1; i++) { arr[i] = Math.random() * 100;//Decimal between [0100) } arr[arr.length-1] = 0; System.out.println("Distance from each point on the line to the next point:"+Arrays.toString(arr)); double length = 150.5; int count = 0; double sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; if(sum<=length) { count++; }else { break; } } System.out.println("Length:" + length + "The rope can cover at most" +count+"Points"); } }
5. Programming question 5
Bubble sort:
public static void bubbleSort(int[] arr) { for (int i = 1; i < arr.length; i++) { for (int j = 0; j < arr.length-i; j++) { if(arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } }
Select Sorting directly:
public static void selectSort(int[] arr) { for (int i = 0; i < arr.length-1; i++) { int minIndex = i; for (int j = i+1; j < arr.length; j++) { if(arr[minIndex] > arr[j]) { minIndex = j; } } if(minIndex!=i) { int temp = arr[minIndex]; arr[minIndex] = arr[i]; arr[i] = temp; } } }
4.4 additional (capable students)
1. Half insert sort
For example: array {12,2,6,1,5}
First time: find the position of inserting 2 between [0,1] = = > left = [0] = > {2,12,6,1,5}
The second time: find the position of inserting 6 between [0,2] = = > left = [1] = = > {2,6,12,1,5}
The third time: find the position of inserting 1 between [0,3] = = > left = [0] = > {1,2,6,12,5}
The fourth time: find the position of inserting 5 between [0,4] = = > left = [2] = > {1,2,5,6,12}
@Test public void test(){ int[] arr = {12,2,6,1,5}; sort(arr); System.out.println(Arrays.toString(arr)); } public void sort(int[] arr){ for (int i=1; i<arr.length; i++){ //Find the location where to insert arr[i] between [0, I] //Use binary search int left = 0; int right=i-1; while (left<=right){ int mid = (left + right)/2; if(arr[i]<=arr[mid]){ right = mid - 1; }else{ left = mid + 1; } } //Insert arr[i] in [0, I] if(left < i){ int temp = arr[i]; System.arraycopy(arr,left,arr,left+1,i-left); arr[left] = temp; } } }
2. Quick sort
For example: array {5, 2, 6, 12, 1, 7, 9}
@Test public void test(){ int[] arr = {5, 2, 6, 12, 1,7,9}; sort(arr,0, arr.length-1); System.out.println(Arrays.toString(arr)); } //Divide the elements between [start+1,end] into two groups. All elements on the left are smaller than arr[start], and all elements on the right are larger than arr[start] public void sort(int[] arr,int start, int end){ if(start < end){ int left = start+1; int right = end; while(left<right){ //From left to right, start from [start+1] to find the number arr[left] larger than arr[start], and exchange it with arr[right] //When arr[left] is greater than arr[start], the loop is stopped because a number larger than arr[start] is found while(arr[left]<=arr[start] && left<=end){ left++; } //From right to left, start from [end] to find the number arr[right] smaller than arr[start], and exchange it with arr[left] //When arr[right] is less than arr[start], the loop is stopped because a smaller number arr[right] than arr[start] is found while(arr[right]>=arr[start] && right>start){ right--; } if(left < right){ int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } } //After the above while, / / if right > start + 1, the number between [start+1,end] is divided into two dials //The number between [start+1,right] is smaller than arr[start] //Between [right,end] is a number larger than arr[start] //Swap arr[start] and arr[right] if(right > start + 1){ int temp = arr[start]; arr[start] = arr[right]; arr[right] = temp; } //At this time, data between [start,right-1] is smaller than arr[start], but they are not sorted //At this time, the data between [right+1,end] is larger than arr[start], but they have not been sorted //Therefore, you need to repeat the above operations for the elements between [start,right-1] and [right+1,end] to continue sorting sort(arr,start,right-1); sort(arr,right+1,end); } }
Call sort for the first time (arr, 0,6)
Exchange arr[left=2] and arr[right=4]: [5, 2, 1, 12, 6, 7, 9]
Exchange elements of reference position and boundary position: arr[start=0] and arr[right=2]: [1, 2, 5, 12, 6, 7, 9]
Call sort for the second time (arr, 0,1)
Call sort for the third time (arr, 0,0)
Call sort for the fourth time (arr, 2,1)
Call sort for the fifth time (arr, 3,6)
Exchange elements of reference position and boundary position: arr[start=3] and arr[right=6]: [1, 2, 5, 9, 6, 7, 12]
Call sort for the 6th time (arr, 3,5)
Exchange elements of reference position and boundary position: arr[start=3] and arr[right=5]: [1, 2, 5, 7, 6, 9, 12]
Call sort for the 7th time (arr, 3,4)
Call sort for the 8th time (arr, 3,3)
The 9th call to sort(arr,5,4)
The 10th call to sort(arr,6,5)
The 11th call to sort(arr,7,6)
5. String
The java.lang.String class represents strings. All string literals (such as "abc") in Java programs can be regarded as instances of implementing this class. Strings are constants; their values cannot be changed after creation. String buffers support variable strings. Because string objects are immutable, they can be shared.
The String class includes methods that can be used to check a single character of a sequence, compare strings, search strings, extract substrings, create a copy of strings, and convert all characters to uppercase or lowercase.
The Java language provides special support for string concatenation ("+") and converting other objects to strings (toString() method).
5.1 characteristics of string
1. The String type itself is declared by final, which means that we cannot inherit String.
2. The object of the string is also an immutable object, which means that once it is modified, a new object will be generated
After we modify the string, if we want to get new content, we must accept it again.
If the program involves a large number of string modification operations, the time and space consumption is relatively high. You may need to consider using the variable character sequence of StringBuilder or StringBuffer.
3. String objects are stored internally in character arrays
There is a char[] value array before JDK1.9 and a byte [] array after JDK1.9
"abc" is equivalent to char [] data = {a ',' B ',' C '}.
For example: String str = "abc"; amount to: char data[] = {'a', 'b', 'c'}; String str = new String(data); // The bottom layer of String is realized by character array.
4. The char[] values array in the String class is also final modified, which means that the array is immutable, and then it is private modified. It cannot be operated directly externally. All the methods provided by the String type use new objects to represent the modified contents, so it ensures the immutability of the String object.
5. Because the string object is designed to be immutable, the string has a constant pool to hold many constant objects
The constant pool is in the method area.
If detailed division:
(1) JDK1.6 and before: method area
(2) JDK1.7: reactor
(3) JDK1.8: meta space
String s1 = "abc"; String s2 = "abc"; System.out.println(s1 == s2); // Only one "abc" object in memory is created and shared by s1 and s2.
5.2 constructing string objects
1. Using construction methods
- public String(): initializes the newly created String object to represent a null character sequence.
- String(String original): initializes a newly created string object to represent the same character sequence as the parameter; in other words, the newly created string is a copy of the parameter string.
- public String(char[] value): construct a new String through the character array in the current parameter.
- public String(char[] value,int offset, int count): construct a new String through a part of the character array.
- public String(byte[] bytes): construct a new String by decoding the byte array in the current parameter using the platform's default character set.
- public String(byte[] bytes,String charsetName): construct a new String by decoding the byte array in the current parameter using the specified character set.
For example, the code is as follows:
//String constant object String str = "hello"; // Nonparametric structure String str1 = new String(); //Create a copy of the "hello" string constant String str2 = new String("hello"); //Constructed from a character array char chars[] = {'a', 'b', 'c','d','e'}; String str3 = new String(chars); String str4 = new String(chars,0,3); // Constructed by byte array byte bytes[] = {97, 98, 99 }; String str5 = new String(bytes); String str6 = new String(bytes,"GBK");
2. Using static methods
- static String copyValueOf(char[] data): returns the String representing the character sequence in the specified array
- static String copyValueOf(char[] data, int offset, int count): returns the String representing the character sequence in the specified array
- static String valueOf(char[] data): returns the String representing the character sequence in the specified array
- static String valueOf(char[] data, int offset, int count): returns the String representing the character sequence in the specified array
- static String valueOf(xx value): xx supports various data types and returns the string representation of the value parameter of various data types.
public static void main(String[] args) { char[] data = {'h','e','l','l','o','j','a','v','a'}; String s1 = String.copyValueOf(data); String s2 = String.copyValueOf(data,0,5); int num = 123456; String s3 = String.valueOf(num); System.out.println(s1); System.out.println(s2); System.out.println(s3); }
3. Use ''+
Any data type is spliced with "string", and the result is string
public static void main(String[] args) { int num = 123456; String s = num + ""; System.out.println(s); Student stu = new Student(); String s2 = stu + "";//Automatically call toString() of the object and splice it with "" System.out.println(s2); }
5.3 number of string objects
1. String constant object
String str1 = "hello";//1 in constant pool
2. The normal object of the string is used together with the constant object
String str3 = new String("hello"); //str3 first points to a string object in the heap, and then the value array of strings in the heap points to the value array of constant objects in the constant pool
5.4 memory analysis of string objects
String s; String s = null; String s = ""; String s = new String(); String s = new String(""); String s = "abc"; String s = new String("abc"); char[] arr = {'a','b'}; String s = new String(arr); char[] arr = {'a','b','c','d','e'}; String s = new String(arr,0,3);
5.5 string splicing
1. Storage and comparison of splicing results
principle:
(1) Constant + constant: the result is a constant pool
(2) Constants and variables or variables and variables: the result is the heap
(3) call intern after splicing: the result is in constant pool.
@Test public void test06(){ String s1 = "hello"; String s2 = "world"; String s3 = "helloworld"; String s4 = (s1 + "world").intern();//Put the splicing results into the constant pool String s5 = (s1 + s2).intern(); System.out.println(s3 == s4);//true System.out.println(s3 == s5);//true } @Test public void test05(){ final String s1 = "hello"; final String s2 = "world"; String s3 = "helloworld"; String s4 = s1 + "world";//s4 string content is also helloworld, s1 is a constant, "world" constant, and constant + constant results are in the constant pool String s5 = s1 + s2;//s5 string contents are also helloworld, s1 and s2 are constants, and constant + constant results are in the constant pool String s6 = "hello" + "world";//Constant + constant results are in the constant pool because the results can be determined during compilation System.out.println(s3 == s4);//true System.out.println(s3 == s5);//true System.out.println(s3 == s6);//true } @Test public void test04(){ String s1 = "hello"; String s2 = "world"; String s3 = "helloworld"; String s4 = s1 + "world";//s4 string content is also helloworld, s1 is a variable, "world" constant, and the result of variable + constant is in the heap String s5 = s1 + s2;//s5 string content is helloworld, s1 and s2 are variables, and the result of variable + variable is in the heap String s6 = "hello" + "world";//Constant + constant results are in the constant pool because the results can be determined during compilation System.out.println(s3 == s4);//false System.out.println(s3 == s5);//false System.out.println(s3 == s6);//true }
2. Splicing efficiency
public class TestString { public static void main(String[] args) { String str = "0"; for (int i = 0; i <= 5; i++) { str += i; } System.out.println(str); } }
However, the current JDK version will use variable character sequence to optimize the above code. Let's decompile and view the bytecode:
javap -c TestString.class
3. Two kinds of splicing
public class TestString { public static void main(String[] args) { String str = "hello"; String str2 = "world"; String str3 ="helloworld"; String str4 = "hello".concat("world"); String str5 = "hello"+"world"; System.out.println(str3 == str4);//false System.out.println(str3 == str5);//true } }
concat method splicing, even if two constant objects are spliced, the result is in the heap.
5.6 comparison of string objects
1. = =: the address of the comparison object
true is returned only if both string variables are constant objects pointing to strings
String str1 = "hello"; String str2 = "hello"; System.out.println(str1 == str2);//true String str3 = new String("hello"); String str4 = new String("hello"); System.out.println(str1 == str4); //false System.out.println(str3 == str4); //false
2. Equals: the comparison is the content of the object, because the String type overrides equals and is case sensitive
As long as the character contents of the two strings are the same, true will be returned
String str1 = "hello"; String str2 = "hello"; System.out.println(str1.equals(str2));//true String str3 = new String("hello"); String str4 = new String("hello"); System.out.println(str1.equals(str3));//true System.out.println(str3.equals(str4));//true
3. equalsIgnoreCase: compares the contents of objects and is not case sensitive
String str1 = new String("hello"); String str2 = new String("HELLO"); System.out.println(str1.equalsIgnoreCase(strs)); //true
4. compareTo: the String type overrides the abstract method of the Comparable interface. It is sorted naturally. It compares the size according to the Unicode encoded value of the character, and is strictly case sensitive
String str1 = "hello"; String str2 = "world"; str1.compareTo(str2) //Values less than 0
5. compareToIgnoreCase: case insensitive. Other characters are compared according to their Unicode encoding values
String str1 = new String("hello"); String str2 = new String("HELLO"); str1.compareToIgnoreCase(str2) //Equal to 0
5.7 comparison of empty characters
1. What are empty strings
String str1 = ""; String str2 = new String(); String str3 = new String("");
Empty string: length 0
2. How to determine whether a string is an empty string
if("".equals(str)) if(str!=null && str.isEmpty()) if(str!=null && str.equals("")) if(str!=null && str.length()==0)
5.8 common methods of string
1. Series 1
(1) boolean isEmpty(): whether the string is empty
(2) int length(): returns the length of the string
(3) String concat(xx): splicing, equivalent to+
(4) boolean equals(Object obj): compares whether strings are equal, case sensitive
(5) boolean equalsIgnoreCase(Object obj): compares whether strings are equal and is case sensitive
(6) int compareTo(String other): compare string sizes, case sensitive, and compare sizes according to Unicode encoded values
(7) int compareToIgnoreCase(String other): compares string sizes, case insensitive
(8) String toLowerCase(): converts uppercase letters to lowercase letters in a string
(9) String toUpperCase(): converts lowercase letters in a string to uppercase
(10) String trim(): remove the white space before and after the string
@Test public void test01(){ //Turn all the words entered by the user into lowercase. If the user does not enter a word, re-enter it Scanner input = new Scanner(System.in); String word; while(true){ System.out.print("Please enter a word:"); word = input.nextLine(); if(word.trim().length()!=0){ word = word.toLowerCase(); break; } } System.out.println(word); } @Test public void test02(){ //Randomly generate verification code, which is composed of characters 0-9, A-Z and A-Z char[] array = new char[26*2+10]; for (int i = 0; i < 10; i++) { array[i] = (char)('0' + i); } for (int i = 10,j=0; i < 10+26; i++,j++) { array[i] = (char)('A' + j); } for (int i = 10+26,j=0; i < array.length; i++,j++) { array[i] = (char)('a' + j); } String code = ""; Random rand = new Random(); for (int i = 0; i < 4; i++) { code += array[rand.nextInt(array.length)]; } System.out.println("Verification Code:" + code); //Turn all the words entered by the user into lowercase. If the user does not enter a word, re-enter it Scanner input = new Scanner(System.in); System.out.print("Please enter the verification code:"); String inputCode = input.nextLine(); if(!code.equalsIgnoreCase(inputCode)){ System.out.println("Incorrect verification code input"); } }
2. Series 2: finding
(11) boolean contains(xx): whether xx is included
(12) int indexOf(xx): find xx in the current string from front to back, that is, if there is a subscript that appears for the first time, if there is no - 1
(13) int lastIndexOf(xx): find xx in the current string from back to front, that is, if there is a subscript that returns the last occurrence, if there is no - 1
@Test public void test01(){ String str = "Shang Silicon Valley is a reliable training institution, and Shang Silicon Valley can be said to be IT Little Tsinghua trained, JavaEE It is the leading discipline of Shang Silicon Valley, and Shang Silicon Valley's big data training is the unicorn of the industry. The front end of Shang Silicon Valley is as dominant as the operation and maintenance specialty."; System.out.println("Whether Tsinghua University is included:" + str.contains("tsinghua")); System.out.println("First subscript of training:" + str.indexOf("train")); System.out.println("Last subscript of training:" + str.lastIndexOf("train")); }
3. Series 3: String interception
(14) String substring(int beginIndex): returns a new string, which is the last substring of the string intercepted from beginIndex.
(15) String substring(int beginIndex, int endIndex): returns a new string, which is a substring intercepted from beginIndex to endindex (excluding).
@Test public void test01(){ String str = "helloworldjavaatguigu"; String sub1 = str.substring(5); String sub2 = str.substring(5,10); System.out.println(sub1); System.out.println(sub2); } @Test public void test02(){ String fileName = "Fast learning Java The secret of.dat"; //Intercept file name System.out.println("File name:" + fileName.substring(0,fileName.lastIndexOf("."))); //Intercept suffix System.out.println("Suffix:" + fileName.substring(fileName.lastIndexOf("."))); }
4. Series 4: character related
(16) char charAt(index): returns the character at [index] position
(17) char[] toCharArray(): convert this string into a new character array and return
(18) String(char[] value): returns the string representing the character sequence in the specified array.
(19) String(char[] value, int offset, int count): returns the string representing the character sequence in the specified array.
(20) static String copyValueOf(char[] data): returns the String representing the character sequence in the specified array
(21) static String copyValueOf(char[] data, int offset, int count): returns the String representing the character sequence in the specified array
(22) static String valueOf(char[] data, int offset, int count): returns the String representing the character sequence in the specified array
(23) static String valueOf(char[] data): returns the String representing the character sequence in the specified array
@Test public void test01(){ //Arranges the characters in a string in size order String str = "helloworldjavaatguigu"; char[] array = str.toCharArray(); Arrays.sort(array); str = new String(array); System.out.println(str); } @Test public void test02(){ //Convert initials to uppercase String str = "jack"; str = Character.toUpperCase(str.charAt(0))+str.substring(1); System.out.println(str); }
5. Series 5: encoding and decoding
(24) byte[] getBytes(): encoding, changing the string into a byte array and encoding according to the default character encoding of the platform
Byte [] GetBytes (character encoding method): encode according to the specified encoding method
(25) new String(byte []) or new String(byte[], int, int): decode according to the default character encoding of the platform
new String(byte [], character encoding method) or new String(byte[], int, int, character encoding method): decode according to the specified encoding method
/* * GBK,UTF-8,ISO8859-1 All character encodings are downward compatible with ASCII codes */ public static void main(String[] args) throws Exception { String str = "China"; System.out.println(str.getBytes("ISO8859-1").length);// 2 // ISO8859-1 treats all characters as a byte and cannot handle multiple bytes System.out.println(str.getBytes("GBK").length);// 4 each Chinese character corresponds to 2 bytes System.out.println(str.getBytes("UTF-8").length);// 6 conventional Chinese is 3 bytes /* * No garbled Code: (1) ensure that the encoded and decoded character set names are the same (2) no missing bytes */ System.out.println(new String(str.getBytes("ISO8859-1"), "ISO8859-1"));// Garbled code System.out.println(new String(str.getBytes("GBK"), "GBK"));// China System.out.println(new String(str.getBytes("UTF-8"), "UTF-8"));// China }
Character coding development
ASCII code
At first, the computer was invented to solve the problem of digital computing. Later, it was found that the computer can do more things, such as text processing. But because the computer only knows "numbers", people must tell the computer which number represents which specific character. For example, 65 represents the letter 'A', 66 represents the letter 'B', and so on. However, the corresponding relationship between characters and numbers between computers must be consistent, otherwise the characters of the same number displayed on different computers will be different. Therefore, the American National Standards Institute ANSI has formulated A standard that specifies the set of common characters and the corresponding number of each character, which is the ASCII Character Set, also known as ASCII code.
At that time, the character encoding and decoding system was very simple, which was a simple table lookup process. Of which:
- 0 ~ 31 and 127 (33 in total) are control characters or special characters for communication (the rest are displayable characters), such as control characters: LF (line feed), CR (enter), FF (page feed), DEL (delete), BS (backspace)
- 32 ~ 126 (95 in total) are characters (32 is spaces), of which 48 ~ 57 are ten Arabic numerals from 0 to 9.
- 65 ~ 90 are 26 capital English letters, 97 ~ 122 are 26 lowercase English letters, and the rest are some punctuation marks, operation symbols, etc.
Derivation of OEM character set
When computers began to develop, people gradually found that the poor 128 characters in the ASCII character set could no longer meet their needs. People were thinking that a byte could represent a number (number) There are 256 ASCII characters, and only 0x00~0x7F are used, that is, the first 128 characters are occupied, and the last 128 numbers are not used in vain. Therefore, many people have the idea of the last 128 numbers. However, the problem is that many people have this idea at the same time, but they have their own ideas about what characters the last 128 numbers 0x80-0xFF correspond to. This leads to A large number of OEM character sets appeared on machines sold all over the world at that time. Different OEM character sets made it impossible for people to communicate various documents across machines. For example, employee a sent a resume R é sum é s to employee B, but employee B saw r?sum?s, because the byte corresponding to the é character in the OEM character set on employee a's machine was 0x82, while in employee B's character set On the machine, due to the different OEM character sets used, the characters obtained after decoding 0x82 bytes are?.
Multi byte character set (MBCS) and Chinese character set
The character sets we mentioned above are based on single byte encoding, that is, one byte is translated into one character. This may not be a problem for Latin speaking countries, because they can get 256 characters by expanding the 8th bit, which is enough. However, for Asian countries, 256 characters are far from enough. Therefore, the number of characters in these countries is not enough In order to use computers and maintain compatibility with ASCII character sets, people invented multi byte coding, and the corresponding character set is called multi byte character set. For example, double byte character set coding is used in China.
For example, the most commonly used Chinese character set GB2312 covers all simplified characters and some other characters; GBK (K stands for extension) Other non simplified characters such as traditional characters are added to GB2312. The characters of these two character sets are represented by 1-2 bytes. Windows system uses 936 code page to encode and decode GBK character set. When parsing byte stream, if the highest bit of a word section is 0, it uses the first code table in 936 code page to decode, which is very important It is consistent with the encoding and decoding method of single byte character set. If the highest byte is 1, it means that two byte values are required to correspond to one character.
ANSI standard, national standard, ISO standard
The emergence of different ASCII derived character sets makes document communication very difficult, so various organizations have successively carried out standardization processes. For example, the American ANSI organization has developed ANSI standard character coding (note that we usually talk about ANSI coding now, which usually refers to the default coding of the platform, such as ISO-8859-1 in the English operating system and GBK in the Chinese system) , various ISO standard character codes developed by ISO organizations, and some countries will also develop some national standard character sets, such as GBK, GB2312 and GB18030 in China.
When the operating system is released, it will normally install these standard character sets into the machine and the special character set of the platform. So long as your document is written with the standard character set, it is more versatile. For example, the document you wrote with the GB2312 character set can be displayed correctly on any machine in the Chinese mainland. At the same time, we can also work on a machine. Read documents in different languages in multiple countries, provided that the character set used in the document must be installed on this computer.
The emergence of Unicode
Although we can access documents in different languages on one machine by using different character sets, we still can't solve a problem: if a document contains characters in different languages of different countries, we can't display all characters in a document. In order to solve this problem, we need a huge character set agreed by all mankind, This is the Unicode character set.
The Unicode character set covers all characters currently used by human beings, and each character is uniformly numbered and assigned a unique Code Point. The Unicode character set divides all characters into 17 planes according to the frequency of use , there are 216 = 65536 character code spaces on each level. BMP, level 0, basically covers all characters used in today's world. Other levels are either used to represent some ancient characters or reserved for expansion. The Unicode characters we usually use are generally located on the BMP level. At present, there are a large number of character spaces not used in the Unicode character set .
Unicode is also not perfect. There are three problems here. One is that we already know that only one byte is enough for English letters. The second problem is how to distinguish Unicode from ASCII? How does the computer know that two bytes represent one symbol instead of two symbols respectively? Third, if the highest bit is 1 or 0 to represent two bytes and one byte, like the double byte encoding method such as GBK, there are many fewer values that cannot be used to represent characters, not enough to represent all characters. Unicode could not be popularized for a long time until the emergence of the Internet. In order to solve the problem of how Unicode is transmitted on the network, many transmission oriented UTF (UCS Transfer Format) standards appeared. As the name suggests, UTF-8 transmits data 8 bits at a time, and UTF-16 transmits data 16 bits at a time. UTF-8 is the most widely used Unicode implementation on the Internet. It is a coding designed for transmission and makes the coding borderless, so that the characters of all cultures in the world can be displayed.
The biggest feature of UTF-8 is that it is a variable length coding method. It can use 1 ~ 4 bytes to represent a symbol. From unicode to uft-8 is not a direct correspondence, but needs some algorithms and rules to convert (that is, the Uncidoe character set ≠ UTF-8 encoding method).
It is not a direct correspondence, but needs to be converted through some algorithms and rules (that is, the Uncidoe character set ≠ UTF-8 encoding method).
Unicode symbol range | UTF-8 encoding method
(HEX) | (binary)
----------—–
0000 0000-0000 007F | 0xxxxxxx (compatible with the original ASCII)
0000 0080-0000 07FF | 110xxxxx 10xxxxxx
0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
Therefore, Unicode only defines a huge and universal character set, and specifies a unique number for each character. The specific byte stream stored depends on the character coding scheme. The recommended Unicode encodings are UTF-16 and UTF-8.
Early concepts such as character coding, character set and code page all expressed the same meaning. For example, GB2312 character set, GB2312 encoding and 936 code page actually mean the same thing.
However, Unicode is different. The Unicode character set only defines the set and unique number of characters. Unicode coding is a general term for specific coding schemes such as UTF-8 and UCS-2/UTF-16, not a specific coding scheme. So when you need character encoding, you can write gb2312, codepage 936, UTF-8, utf-16, but please don't write Unicode.
6. Series 6: beginning and end
(26) boolean startsWith(xx): whether it starts with xx
(27) boolean endsWith(xx): whether it ends with xx
@Test public void test2(){ String name = "Zhang San"; System.out.println(name.startsWith("Zhang")); } @Test public void test(){ String file = "Hello.txt"; if(file.endsWith(".java")){ System.out.println("Java source file"); }else if(file.endsWith(".class")){ System.out.println("Java Bytecode file"); }else{ System.out.println("Other documents"); } }
8. Series 8: replacement
(29) String replace(xx,xx): regular is not supported
(30) string replacefirst (regular, value): replace the first matching part
(31) string repalceall (regular, value): replace all matching parts
@Test public void test4(){ String str = "hello244world.java;887"; //Remove the non letters from it str = str.replaceAll("[^a-zA-Z]", ""); System.out.println(str); }
9. Series 9: split
(32) string [] split (regular): split according to certain rules
@Test public void test4(){ String str = "Zhang San.23|Li Si.24|Wang Wu.25"; //|It has a special meaning in regularization, and I'll treat it as ordinary here| String[] all = str.split("\\|"); //Turn into a student object Student[] students = new Student[all.length]; for (int i = 0; i < students.length; i++) { //It has a special meaning in regular, and I want to express ordinary here String[] strings = all[i].split("\\.");//Zhang San, 23 String name = strings[0]; int age = Integer.parseInt(strings[1]); students[i] = new Student(name,age); } for (int i = 0; i < students.length; i++) { System.out.println(students[i]); } } @Test public void test3(){ String str = "1Hello2World3java4atguigu5"; str = str.replaceAll("^\\d|\\d$", ""); String[] all = str.split("\\d"); for (int i = 0; i < all.length; i++) { System.out.println(all[i]); } } @Test public void test2(){ String str = "1Hello2World3java4atguigu"; str = str.replaceFirst("\\d", ""); System.out.println(str); String[] all = str.split("\\d"); for (int i = 0; i < all.length; i++) { System.out.println(all[i]); } } @Test public void test1(){ String str = "Hello World java atguigu"; String[] all = str.split(" "); for (int i = 0; i < all.length; i++) { System.out.println(all[i]); } }
6. Variable character sequence
6.1 difference between string and variable character sequence
Because String objects are immutable objects, although constant objects can be shared, they are extremely inefficient for frequent String modification and splicing operations. Therefore, JDK also provides variable character sequence StringBuilder and StringBuffer types in java.lang package.
StringBuffer: old, thread safe (because its method is decorated with synchronized)
StringBuilder: thread unsafe
6.2 API of StringBuilder and StringBuffer
The common API s, StringBuilder and StringBuffer, are identical
(1) StringBuffer append(xx): splice, append
(2) StringBuffer insert(int index, xx): insert xx at [index]
(3) StringBuffer delete(int start, int end): deletes characters between [start, end]
StringBuffer deleteCharAt(int index): deletes the [index] position character
(4) void setCharAt(int index, xx): replace the [index] position character
(5) StringBuffer reverse(): reverse
(6) void setLength(int newLength): sets the length of the current character sequence to newLength
(7) StringBuffer replace(int start, int end, String str): replace the character sequence in the [start,end) range as str
(8) int indexOf(String str): query the first occurrence of the subscript of str in the current character sequence
int indexOf(String str, int fromIndex): query the index of str for the first time in the current character sequence [fromIndex, last]
int lastIndexOf(String str): query the last occurrence of the subscript of str in the current character sequence
int lastIndexOf(String str, int fromIndex): query the last occurrence subscript of str in the current character sequence [fromIndex, last]
(9) String substring(int start): intercepts the current character sequence [start, last]
(10) String substring(int start, int end): intercept the current character sequence [start, end]
(11) String toString(): returns the string representation of the data in this sequence
@Test public void test6(){ StringBuilder s = new StringBuilder("helloworld"); s.setLength(30); System.out.println(s); } @Test public void test5(){ StringBuilder s = new StringBuilder("helloworld"); s.setCharAt(2, 'a'); System.out.println(s); } @Test public void test4(){ StringBuilder s = new StringBuilder("helloworld"); s.reverse(); System.out.println(s); } @Test public void test3(){ StringBuilder s = new StringBuilder("helloworld"); s.delete(1, 3); s.deleteCharAt(4); System.out.println(s); } @Test public void test2(){ StringBuilder s = new StringBuilder("helloworld"); s.insert(5, "java"); s.insert(5, "chailinyan"); System.out.println(s); } @Test public void test1(){ StringBuilder s = new StringBuilder(); s.append("hello").append(true).append('a').append(12).append("atguigu"); System.out.println(s); System.out.println(s.length()); }
6.3 efficiency test
/* * Runtime: JVM Runtime environment * Runtime Is a singleton implementation */ public class TestTime { public static void main(String[] args) { // testStringBuilder(); testStringBuffer(); // testString(); } public static void testString(){ long start = System.currentTimeMillis(); String s = new String("0"); for(int i=1;i<=10000;i++){ s += i; } long end = System.currentTimeMillis(); System.out.println("String Splicing+Time:"+(end-start));//444 long memory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); System.out.println("String Splicing+memory Occupied memory: " + memory);//53185144 bytes } public static void testStringBuilder(){ long start = System.currentTimeMillis(); StringBuilder s = new StringBuilder("0"); for(int i=1;i<=10000;i++){ s.append(i); } long end = System.currentTimeMillis(); System.out.println("StringBuilder Splicing+Time:"+(end-start));//4 long memory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); System.out.println("StringBuilder Splicing+memory Occupied memory: " + memory);//1950488 } public static void testStringBuffer(){ long start = System.currentTimeMillis(); StringBuffer s = new StringBuffer("0"); for(int i=1;i<=10000;i++){ s.append(i); } long end = System.currentTimeMillis(); System.out.println("StringBuffer Splicing+Time:"+(end-start));//7 long memory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); System.out.println("StringBuffer Splicing+memory Occupied memory: " + memory);//1950488 } }
7. Interview questions related to string characteristics
1. Interview question: what is the difference between the length of a string and the length of an array?
length() of string, length attribute of array
2. String object immutable

class TEXT{ public int num; public String str; public TEXT(int num, String str){ this.num = num; this.str = str; } } public class Class4 { //tIn is the address of the transfer object. Modifying the properties of the formal parameter will affect the actual parameter //intIn is passed data, and the modification of formal parameters of basic data type is independent of actual parameters //Integer and String objects are immutable public static void f1(TEXT tIn, int intIn, Integer integerIn, String strIn){ tIn.num =200; tIn.str = "bcd";//The formal parameter and the argument point to the same TEXT object. Modifying the attribute is equivalent to modifying the attribute of the argument object intIn = 200;//A formal parameter of a basic data type is a "copy" of an argument. No matter how it is modified, it has nothing to do with the argument integerIn = 200;//Integer objects, like String objects, are immutable. Once modified, they are new objects and have nothing to do with arguments strIn = "bcd"; } public static void main(String[] args) { TEXT tIn = new TEXT(100, "abc");//tIn.num = 100, tIn.str="abc" int intIn = 100; Integer integerIn = 100; String strIn = "abc"; f1(tIn,intIn,integerIn,strIn); System.out.println(tIn.num + tIn.str + intIn + integerIn + strIn); //200 + bcd + 100 + 100 + abc } }
3. Number of string objects
4. String object comparison
5. Empty string
8. String algorithm related interview questions
1. Programming problem
Find the longest consecutive number string in the string, return the length of the string, and print the longest number string.
For example, abcd12345cd125se123456789 returns 9 and prints 123456789
public class TestExer1 { public static void main(String[] args) { String str = "abcd12345cd125se123456789"; //Remove the first and last letters str = str.replaceAll("^[a-zA-Z]+", ""); //[a-zA-Z]: indicates the letter range //+: one or more String[] strings = str.split("[a-zA-Z]+"); String max = ""; for (String string : strings) { if(string.length() > max.length()) { max = string; } } System.out.println("Longest number string:" + max + ",Its length is:" + max.length()); } }
2. Programming problem
You cannot use trim() to remove spaces at both ends of a string.
public static void main(String[] args) { String str =" he llo "; System.out.println(myTrim(str)); System.out.println(myTrim2(str)); System.out.println(myTrim3(str)); } public static String myTrim3(String str){ //Using regular expressions //^Indicates the beginning \ s indicates the blank character * indicates 0 or more times | indicates or $indicates the end return str.replaceAll("(^\\s*)|(\\s*$)", ""); } public static String myTrim2(String str){ while(str.startsWith(" ")){ str = str.replaceFirst(" ", ""); } while(str.endsWith(" ")){ str = str.substring(0, str.length()-1); } return str; } public static String myTrim(String str){ char[] array = str.toCharArray(); int start =0; for(int i=0;i<array.length;i++){ if(array[i] == ' '){ start++; }else{ break; } } int end = array.length-1; for(int i=end;i>=0;i--){ if(array[i] == ' '){ end--; }else{ break; } } String result = str.substring(start,end+1); return result; }
3. Programming problem
Inverts the specified part of the string. For example, reverse "abcdefgho" to "abfedcgho"
public static void main(String[] args) { String str ="abcdefgho"; System.out.println(str); System.out.println(reverse(str,2,5)); } //From the start character to the end character public static String reverse(String str,int start,int end){ char[] array = str.toCharArray(); for(int i = start,j=end;i< j;i++,j--){ char temp =array[i]; array[i]=array[j]; array[j]=temp; } String s = new String(array); return s; } //From the start character to the end character public static String reverse(String str,int start,int end){ String left = str.substring(0,start); String middle = str.substring(start,end+1); String left = str.substring(end+1); return left+new StringBuilder(middle).reverse()+right; }
4. Programming problem
Gets the number of occurrences of one string in another string.
For example, get the number of occurrences of "ab" in "ababkkadkabkebfkabkskab"
public static void main(String[] args) { String str1="ab"; String str2="abababkkcadkabkebfkabkskab"; System.out.println(count(str1,str2)); } public static int count(String str1,String str2){ int count =0; do{ int index = str2.indexOf(str1); if(index !=-1){ count++; str2 = str2.substring(index + str1.length()); }else{ break; } }while(true); return count; }
5. Programming problem
Gets the largest identical substring in two strings.
For example: STR1 = "abcwertelloyuodef"; str2 = "cvhellobnm"
Tip: compare the short string with the substring whose length decreases in turn with the longer string.
public static void main(String[] args) { String str=findMaxSubString("abcwerthelloyuiodef","cvhellobnm"); System.out.println(str); } //Tip: compare the short string with the substring whose length decreases in turn with the longer string. public static String findMaxSubString(String str1,String str2){ String result=""; String mixStr = str1.length()<str2.length()?str1:str2; String maxStr = str1.length()>str2.length()?str1:str2; //The outer loop controls the subscript from left to right, and the inner loop controls the subscript from right to left for(int i=0;i<mixStr.length();i++){ for(int j=mixStr.length();j>=i;j--){ String str=mixStr.substring(i, j); if(maxStr.contains(str)){ //Find the largest identical substring if(result.length()<str.length()){ result = str; } } } } return result; }
6. Programming problem
Write code to complete the following functions
public static String replace(String text, String target, String replace){
...
}
Example: replace("aabbccbb", "bb", "dd"); result: aaddccdd
Note: existing replacement API methods such as replace of classes such as String and StringBuffer cannot be used.
public static void main(String[] args) { System.out.println(replace("aabbcbcbb","bb","dd")); } public static String replace(String text, String target, String replace){ while(true) { int index = text.indexOf(target); if(index!=-1) { text = text.substring(0,index) + replace + text.substring(index+target.length()); }else { break; } } return text; }
7. Programming problem
A string may contain multiple characters in a-z, and the characters may be repeated. For example: String data = "aabcexmkduyruieiopxzkkkasdfjxjdsds"; write a program to find the letter with the most occurrences of the string and the number of occurrences for a given string (if there are more than one letter with the most occurrences, find all)
public static void main(String[] args) { String str = "aabbyolhljlhlxxmnbwyteuhfhjloiqqbhrg"; //Count the number of times per letter int[] counts = new int[26]; char[] letters = str.toCharArray(); for (int i = 0; i < letters.length; i++) { counts[letters[i]-97]++; } //Find the most frequent value int max = counts[0]; for (int i = 1; i < counts.length; i++) { if(max < counts[i]) { max = counts[i]; } } //Find all the most frequent letters for (int i = 0; i < counts.length; i++) { if(counts[i] == max) { System.out.println((char)(i+97)); } } }
After learning the set, you can also use the Map set to write different answers to this question
8. Programming problem
Suppose that the date period is represented by two positive integers with a length of 6 bits, for example: (201401201406) used to represent January 2014 to June 2014, and calculate the number of overlapping months of the two date periods. For example, input: time periods 1:201401 and 201406, time periods 2:201403 and 201409, output: 4
Explanation: overlapping months: March, April, may and June, 4 months in total
Scenario 1: both time periods are within the same year, and the implementation code is as follows:
public static void main(String[] args) { String date1Start = "201401"; String date1End = "201406"; String date2Start = "201403"; String date2End = "201409"; int date1StartMonth = Integer.parseInt(date1Start.substring(4)); int date1EndMonth = Integer.parseInt(date1End.substring(4)); int date2StartMonth = Integer.parseInt(date2Start.substring(4)); int date2EndMonth = Integer.parseInt(date2End.substring(4)); int start = date1StartMonth >= date2StartMonth ? date1StartMonth : date2StartMonth; int end = date1EndMonth <= date2EndMonth ? date1EndMonth : date2EndMonth; System.out.println("Number of overlapping months:"+(end-start+1)); System.out.println("Overlapping months are:"); for (int i = start; i <= end; i++) { System.out.println(i); } }
Scenario 2: if the two time periods may not be in the same year, the implementation code is as follows:
public static void main(String[] args) { String date1Start = "201401"; String date1End = "201506"; String date2Start = "201403"; String date2End = "201505"; String date1 = handleDate(date1Start,date1End); String date2 = handleDate(date2Start,date2End); System.out.println(date1); System.out.println(date2); String sameDate = findMaxSubString(date1,date2); System.out.println("Number of overlapping months:" + sameDate.length()/6); if (!"".equals(sameDate)) { System.out.println("Overlapping months are:"); while (sameDate.length() > 0) { String sameMonth = sameDate.substring(0, 6); System.out.println(sameMonth); sameDate = sameDate.substring(6); } } } public static String findMaxSubString(String str1,String str2){ String result=""; String mixStr = str1.length()<str2.length()?str1:str2; String maxStr = str1.length()>str2.length()?str1:str2; //The outer loop controls the subscript from left to right, and the inner loop controls the subscript from right to left for(int i=0;i<mixStr.length();i++){ for(int j=mixStr.length();j>=i;j--){ String str=mixStr.substring(i, j); if(maxStr.contains(str)){ //Find the largest identical substring if(result.length()<str.length()){ result = str; } } } } return result; } public static String handleDate(String dateStart, String dateEnd) { int dateStartYear = Integer.parseInt(dateStart.substring(0,4)); int dateEndYear = Integer.parseInt(dateEnd.substring(0,4)); int dateStartMonth = Integer.parseInt(dateStart.substring(4)); int dateEndMonth = Integer.parseInt(dateEnd.substring(4)); String date = ""; if(dateStartYear == dateEndYear) {//Within a year for (int i = dateStartMonth; i <=dateEndMonth; i++) { if(i<10) { date += dateStartYear+"0"+i; }else { date += dateStartYear+""+i; } } }else {//straddle old and new years for (int i = dateStartMonth; i <=12; i++) {//date1StartYear start year if(i<10) { date += dateStartYear+"0"+i; }else { date += dateStartYear+""+i; } } for (int i = dateStartYear+1; i < dateEndYear; i++) {//Intermediate interval year for (int j = 1; j <= 12; j++) { if(j<10) { date += i+"0"+j; }else { date += i+""+j; } } } for (int i = 1; i <= dateEndMonth; i++) {//date1EndYear end year if(i<10) { date += dateEndYear+"0"+i; }else { date += dateEndYear+""+i; } } } return date; } }