Chapter 3 : Core Java APIs

2021-03-06 23:30

阅读:745

标签:ref   long   system   offset   cond   bec   gen   indexof   format   

Chapter 3 : Core Java APIs

Class String

API stands for application programming interface.


  1. If both operands are numeric, + means numeric addition.

  2. If either operand is a String, + means concatenation.

  3. The expression is evaluated left to right.


Immutability


The string pool, also known as the intern pool, is a location in the Java virtual machine (JVM) that collects all these strings.


methods

thirteen methods from the String class:

  1. int length()

  2. char charAt(int index)

  3. int indexOf() looks at the characters in the string and finds the first index that matches the desired value. indexOf can work with an individual character or a whole String as input. It can also start from a requested position:

    int indexOf(char ch)
    int indexOf(char ch, index fromIndex) 
    int indexOf(String str)
    int indexOf(String str, index fromIndex)
    

    returns –1 when no match is found

  4. String substring() returns the string starting from the requested index. If an end index is requested, it stops right before that index. Otherwise, it goes to the end of the string.

    String substring(int beginIndex)
    String substring(int beginIndex, int endIndex)
    

    index of the number of size is the “end of string” invisible position

  5. String toLowerCase(String str)
    String toUpperCase(String str)
    
  6. boolean equals(String str)
    boolean equalsIgnoreCase(String str) 
    
  7. boolean startsWith(String     prefix)
    boolean endsWith(String suffix)
    
  8. bollean contains() //looks for matches in the String
    boolean contains(String str)
    
  9. String replace() //does a simple search and replace on the string.
    String replace(char oldChar, char newChar)
    String replace(CharSequence oldChar, CharSequence newChar)
    

    CharSequence is an interface representing several classes, including String and StringBuilder

  10. String trim() removes whitespace from the beginning and end of a String. whitespace consists of spaces along with the \t (tab) and \n (newline) \r (carriage return) characters etc.

    public String trim()
    

+和concat

+和concat都可以用来拼接字符串, differences:

  1. +可以是字符串或者数字及其他基本类型数据,而concat只能接收字符串。
  2. +左右可以为null,concat为会空指针。
  3. 如果拼接空字符串,concat会稍快,在速度上两者可以忽略不计,如果拼接更多字符串建议用StringBuilder。
  4. 从字节码来看+号编译后就是使用了StringBuiler来拼接,所以一行+的语句就会创建一个StringBuilder,多条+语句就会创建多个,所以为什么建议用StringBuilder的原因


Class StringBuilder

Unlike the String class, StringBuilder is not immutable.

The StringBuilder class creates a String without storing all those interim String values


There are three ways to construct a StringBuilder:

StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder("animal");
StringBuilder sb3 = new StringBuilder(10);

Size is the number of characters currently in the sequence,

capacity is the number of characters the sequence can currently hold.

methods

  1. char charAt();
    int indexOf();
    int length();
    String substring();
    
  2. StringBuilder append(String str)  //adds the parameter to the StringBuilder and returns a reference to the current StringBuilder. 
    

    There are more than 10 method signatures that look similar but that take different data types as parameters

  3. StringBuilder insert(int offset, String str)
    

    The insert() method adds characters to the StringBuilder at the requested index and returns a reference to the current StringBuilder.

    there are lots of method signatures for different types

  4. StringBuilder delete(int start, int end)
    StringBuilder deleteCharAt(int index)
    //remove characters from the sequence and returns a reference to the current StringBuilder
    
  5. StringBuilder reverse()  //reverses the characters in the sequences and returns a reference to the current StringBuilder
    
  6. String toString()  //converts a StringBuilder into a String
    

When writing new code that concatenates a lot of String objects together, you should use StringBuilder. StringBuilder was added to Java in Java 5. If you come across older code, you will see StringBuffer used for this purpose. StringBuffer does the same thing but more slowly because it is thread safe.


Tricky example:

String x = "Hello World"; 
String z = " Hello World".trim();
System.out.println(x == z); // false

In this example, we don’t have two of the same String literal. Although x and z happen to evaluate to the same string, one is computed at runtime. Since it isn’t the same at compile-time, a new String object is created.


Class StringBuilder does not override the method equals() in Class Object. Calling equals() on StringBuilder objects will check whether they are pointing to the same object rather than looking at the values inside.



Array

It is never legal to include the size of the array in your declaration. Remember, the JVM doesn’t allocate space until you actually instantiate the array object. That’s when size matters.


int ids[], types;

we get one variable of type int[] and one variable of type int. Java sees this line of code and thinks something like this: “They want two variables of type int. The first one is called ids[]. This one is a int[] called ids. The second one is just called types. No brackets, so it is a regular integer.”


int is a primitive; int[] is an object

The equals() method on arrays does not look at the elements of the array. An array does not override equals() and so uses object equality.


The array does not allocate space for the String objects. Instead, it allocates space for a reference to where the objects are really stored


array.length does not consider what is in the array; it only considers how many slots have been allocated


import java.util.Arrays

void Arrays.sort(array);

int Arrays.binarySearch(array, key);
Scenario Result
Target element found in sorted array Index of match
Target element not found in sorted array Negative value showing one smaller than the negative of index, where a match needs to be inserted to preserve sorted order
Unsorted array this result isn’t predictable

varargs

public static void main(String[] args) 

public static void main(String args[]) 

public static void main(String... args)

varargs are arrays so we need to work with them just like we‘d work with a normal array


Varargs are straightforward to use. But there‘re a few rules we have to keep in mind:

  • Each method can only have one varargs parameter
  • The varargs argument must be the last parameter

Using varargs can lead to so-called Heap Pollution


The varargs usage is safe if and only if:

  • We don‘t store anything in the implicitly created array. In this example, we did store a List in that array
  • We don‘t let a reference to the generated array escape the method (more on this later)

Multidimensional Array

create an asymmetric array is to initialize just an array’s first dimension, and define the size of each array component in a separate statement:

int [][] args = new int[4][]; 

args[0] = new int[5]; 

args[1] = new int[3];

it is legal to leave out the size for later dimensions of a multidimensional array, the first one is required

int[][] twoD = new int[3][2];

for (int[] inner : twoD){

	for (int num : inner)

	System.out.print(num + " "); 

	System.out.println();
}

Remember that you do not specify a size when using anonymous array creation syntax.


It’s tempting to assume that because a variable of type byte, short, or char can be explicitly promoted and assigned to an int, an array of any of those types could be assigned to an int array. You can’t do that in Java. Arrays that hold object references, as opposed to primitives, aren’t as restrictive.



Class ArrayList

import java.util.ArrayList;

create an ArrayList:

ArrayList list1 = new ArrayList(); 
ArrayList list2 = new ArrayList(10); 
ArrayList list3 = new ArrayList(list2);
ArrayList list4 = new ArrayList(); 
ArrayList list5 = new ArrayList();

methods

If you didn’t specify a type when creating the ArrayList, E means Object. Otherwise, it means the class you put between .

  1. add() methods insert a new value in the ArrayList.

    boolean add(E element) 
    void add(int index, E element)
    

    It always returns true. It is there because other classes in the collections family need a return value in the signature when adding an element.

  2. remove() methods remove the first matching value in the ArrayList or remove the element at a specified index.

    boolean remove(Object object) 
    E remove(int index)
    

    the boolean return value tells us whether a match was removed.

    The E return type is the element that actually got removed.

  3. set() method changes one of the elements of the ArrayList without changing the size.

    E set(int index, E newElement)
    

    The E return type is the element that got replaced.

  4. boolean isEmpty() 
    int size()
    
  5. void clear()
    
  6. contains() method checks whether a certain value is in the ArrayList.

    boolean contains(Object object)
    

    This method calls equals() on each element of the ArrayList to see whether there are any matches.

  7. equals() compare two lists to see if they contain the same elements in the same order.

    boolean equals(Object object)
    /**********/
    ArrayList list4=new ArrayList(9);
    ArrayList list5=new ArrayList(8);
    Boolean b1 = list4.equals(list5); // true
    

tables

技术图片

技术图片


Autoboxing

ArrayLists hold only object references, not actual objects and not primitives,so there is autobox.

type the primitive value and Java will convert it to the relevant wrapper class for you, this is called autoboxing;

type the wrapper class object and Java will unbox it.


In order to save memory, two instances of the following wrapper objects (created through boxing) will always be == when their primitive values are the same:

  • Boolean
  • Byte
  • Character from \u0000 to \u007f (7f is 127 in decimal)
  • Short and Integer from –128 to 127

When == is used to compare a primitive to a wrapper, the wrapper will be unwrapped and the comparison will be primitive to primitive.


List heights = new ArrayList();
heights.add(null);
int h = heights.get(0); // NullPointerException

On line 4, we add a null to the list. This is legal because a null reference can be assigned to any reference variable. On line 5, we try to unbox that null to an int primitive. This is a problem. Java tries to get the int value of null. Since calling any method on null gives a NullPointerException, that is just what we get.


List numbers = new ArrayList(); 
numbers.add(1); 
numbers.add(2); 
numbers.remove(1); //index 1
System.out.println(numbers);

Becaues there’s already a remove() method that takes an int parameter, Java calls that method rather than autoboxing. If you want to remove the 2, you can write numbers.remove(new Integer(2)) to force wrapper class use.


Converting Between array and List

  1. toArray()
    toArray(Object[] a)
        
    /*********/
        
    List list = new ArrayList(); 
    list.add("hawk");
    list.add("robin");
    Object[] objectArray = list.toArray();
    System.out.println(objectArray.length); // 2
    String[] stringArray = list.toArray(new String[0]);
    System.out.println(stringArray.length); // 2
    

    Line 6 shows that an ArrayList knows how to convert itself to an array. The only problem is that it defaults to an array of class Object. This isn’t usually what you want. Line 8 specifi es the type of the array and does what we actually want. The advantage of specifying a size of 0 for the parameter is that Java will create a new array of the proper size for the return value. If you like, you can suggest a larger array to be used instead. If the ArrayList fi ts in that array, it will be returned. Otherwise, a new one will be created.

  2. Arrays.asList(T… a) accept array and varags

    The original array and created array backed List are linked. When a change is made to one, it is available in the other. It is a fixed-size list and is also known a backed List because the array changes with it.

    String[] array = { "hawk" ,  "robin"}  // [hawk, robin]
    List list = Arrays.asList(array); // returns fixed size list  
    System.out.(list.size()); //2 
    list.set(1, "test"); // [hawk, test]  
    array[0] = "new";  // [new, test]  
    for (String b : array)
        System. out.print(b + " ");  // new test  
    list. remove (1);  // throws UnsupportedOperation Exception
    

    Line 21 converts the array to a List. Note that it isn’t the java.util.ArrayList we’ve grown used to. It is java.util.Arrays.ArrayList, a fixed-size, backed version of a List.

    Line 23 is okay because set() merely replaces an existing value. It updates both array and list because they point to the same data store.

    Line 24 also changes both array and list. Line 25 shows the array has changed to new test.

    Line 26 throws an exception because we are not allowed to change the size of the list.


Collections.sort()


Dates and Times

import java.time.*;

Classes

  • LocalDate
  • LocalTime
  • LocalDateTime
  • ZonedDateTime

The date and time classes have private constructors to force you to use the static methods. You are not allowed to construct a date or time object directly. the exam’s date and time classes use factory methods to create new objects.

The date and time classes are immutable.

Methods

  • public static LocalDate now();
    
  • public static LocalDate of(int year, int month, int dayOfMonth) 
    public static LocalDate of(int year, Month month, int dayOfMonth)
    
    public static LocalTime of(int hour, int minute) 
    public static LocalTime of(int hour, int minute, int second) 
    public static LocalTime of(int hour, int minute, int second, int nanos)
    
    public static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute) 
    public static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second) 
    public static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanos) 
    
    public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute)
    public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second) 
    public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanos) 
    
    public static LocalDateTime of(LocalDate date, LocalTime)
    

    when you pass invalid numbers to of(), throw java.time.DateTimeException.

技术图片

  • Manipulating

技术图片


Class Period

There are five ways to create a Period class:

// every 1 year
Period annually = Period.ofYears(1);
// every 3 months
Period quarterly = Period.ofMonths(3);
// every 3 weeks
Period everyThreeWeeks = Period.ofWeeks(3);
// every 2 days
Period everyOtherDay = Period.ofDays(2); 
// every year and 7 days
Period everyYearAndAWeek = Period.of(1, 0, 7);

There is also Duration, which is intended for smaller units of time. For Duration, you can specify the number of days, hours, minutes, seconds, or nanoseconds.

You cannot chain methods when creating a Period. Otherwise, only the last method is used because the Period.ofXXX methods are static methods.

eg.
技术图片

Line 9 attempts to add a month to an object that only has a time. This won’t work. Java throws an exception and complains that we attempt to use an Unsupported unit: Months.


Formatting

import java.time.format.DateTimeFormatter;

The String format() method is declared on both the formatter objects and the date/time objects, allowing you to reference the objects in either order. The following statements print exactly the same thing:

技术图片

技术图片

技术图片


ofPattern()

DateTimeFormatter f = DateTimeFormatter.ofPattern("MMMM dd, yyyy, hh:mm"); 
System.out.println(dateTime.format(f));  // January 20, 2020, 11:12

M represents the month. The more Ms you have, the more verbose the Java output. For example, M outputs 1, MM outputs 01, MMM outputs Jan, and MMMM outputs January.

y represents the year. yy outputs a two-digit year and yyyy outputs a four-digit year.

parse()

parse() converts a String to a date or time, takes a formatter as well. If you don’t specify one, it uses the default for that type.

eg.:
技术图片



Chapter 3 : Core Java APIs

标签:ref   long   system   offset   cond   bec   gen   indexof   format   

原文地址:https://www.cnblogs.com/leon1994/p/14286947.html


评论


亲,登录后才可以留言!