Chapter 3 : Core Java APIs
2021-03-06 23:30
标签:ref long system offset cond bec gen indexof format API stands for application programming interface. If both operands are numeric, + means numeric addition. If either operand is a String, + means concatenation. 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. thirteen methods from the String class: returns –1 when no match is found index of the number of size is the “end of string” invisible position CharSequence is an interface representing several classes, including String and StringBuilder 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. +和concat都可以用来拼接字符串, differences: 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: Size is the number of characters currently in the sequence, capacity is the number of characters the sequence can currently hold. There are more than 10 method signatures that look similar but that take different data types as parameters 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 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: 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. 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. 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 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: Using varargs can lead to so-called Heap Pollution The varargs usage is safe if and only if: 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: it is legal to leave out the size for later dimensions of a multidimensional array, the first one is required 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. If you didn’t specify a type when creating the ArrayList, E means Object. Otherwise, it means the class you put between . 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. the boolean return value tells us whether a match was removed. The E return type is the element that actually got removed. The E return type is the element that got replaced. This method calls equals() on each element of the ArrayList to see whether there are any matches. 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: When == is used to compare a primitive to a wrapper, the wrapper will be unwrapped and the comparison will be primitive to primitive. 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. 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 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. 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. 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. 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. when you pass invalid numbers to of(), throw java.time.DateTimeException. There are five ways to create a Period class: 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. The 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() 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.htmlChapter 3 : Core Java APIs
Class String
methods
int length()
char charAt(int index)
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)
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)
String toLowerCase(String str)
String toUpperCase(String str)
boolean equals(String str)
boolean equalsIgnoreCase(String str)
boolean startsWith(String prefix)
boolean endsWith(String suffix)
bollean contains() //looks for matches in the String
boolean contains(String str)
String replace() //does a simple search and replace on the string.
String replace(char oldChar, char newChar)
String replace(CharSequence oldChar, CharSequence newChar)
public String trim()
+和concat
Class StringBuilder
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder("animal");
StringBuilder sb3 = new StringBuilder(10);
methods
char charAt();
int indexOf();
int length();
String substring();
StringBuilder append(String str) //adds the parameter to the StringBuilder and returns a reference to the current StringBuilder.
StringBuilder insert(int offset, String str)
StringBuilder delete(int start, int end)
StringBuilder deleteCharAt(int index)
//remove characters from the sequence and returns a reference to the current StringBuilder
StringBuilder reverse() //reverses the characters in the sequences and returns a reference to the current StringBuilder
String toString() //converts a StringBuilder into a String
String x = "Hello World";
String z = " Hello World".trim();
System.out.println(x == z); // false
Array
int ids[], types;
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)
Multidimensional Array
int [][] args = new int[4][];
args[0] = new int[5];
args[1] = new int[3];
int[][] twoD = new int[3][2];
for (int[] inner : twoD){
for (int num : inner)
System.out.print(num + " ");
System.out.println();
}
Class ArrayList
import java.util.ArrayList;
create an ArrayList:
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList(10);
ArrayList list3 = new ArrayList(list2);
ArrayList
methods
add()
methods insert a new value in the ArrayList.boolean add(E element)
void add(int index, E element)
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)
set()
method changes one of the elements of the ArrayList without changing the size.E set(int index, E newElement)
boolean isEmpty()
int size()
void clear()
contains()
method checks whether a certain value is in the ArrayList.boolean contains(Object object)
equals()
compare two lists to see if they contain the same elements in the same order.boolean equals(Object object)
/**********/
ArrayList
tables
Autoboxing
List
List
numbers.remove(new Integer(2))
to force wrapper class use.
Converting Between array and List
toArray()
toArray(Object[] a)
/*********/
List
Arrays.asList(T… a)
accept array and varagsString[] array = { "hawk" , "robin"} // [hawk, robin]
List
Collections.sort()
Dates and Times
import java.time.*;
Classes
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)
Class Period
// 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);
Formatting
import java.time.format.DateTimeFormatter;
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
parse()
文章标题:Chapter 3 : Core Java APIs
文章链接:http://soscw.com/index.php/essay/61084.html