目录
1.不可变对象和类 Immutable Objects and Classes
4.类抽象和封装 Class Abstraction and Encapsulation
4.1.2字符串长度、字符和组合字符串 String Length, Characters, and Combining Strings
4.1.3 提取子字符串 Extracting Substrings
4.1.4在字符串中查找字符或子字符串 Finding a Character or a Substring in a String
4.1.5匹配、转换、替换和分割字符串 Converting, Replacing, and Splitting Strings
4.1.6按模式(正则表达式)匹配、替换和分割Matching, Replacing and Splitting by Patterns
4.1.7命令行参数 Command-Line Parameters
4.2 StringBuilder/StringBuffer
1.不可变对象和类 Immutable Objects and Classes
1.1定义
- 不可变对象:一旦对象被创建,其内容就不能被更改。
Immutable object: the contents of an object cannot be changed once the object is created
- 不可变类:包含不可变对象的类被称为不可变类。
- 示例(不可变类):
·在Circle类中没有提供 set 方法,因此它是一个不可变类。
1.2 判断
- 一个不可变类必须满足以下条件:
·必须将所有数据字段标记为私有(It must mark all data fields private!
·不提供任何修改器(set)方法!Provide no mutator (set) methods!
·不提供任何会返回可变数据字段对象引用的访问器(getter)方法!Provide no accessor methods that would return a reference to a mutable data field object!
2.变量作用域 Scope of Variables
- 局部变量的作用域从其声明开始,并持续到包含该变量的代码块的末尾。The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable
·此外,局部变量在使用之前必须显式初始化。Also a local variable must be initialized explicitly before it can be used
- 数据字段变量可以在类内的任何地方声明 Data Field Variables can be declared anywhere inside a class
·实例变量和静态变量的作用域是整个类!The scope of instance and static variables is the entire class!
·它们会使用默认值进行初始化。Initialized with default values.
3.this关键字 The this Keyword
- this关键字是一个引用的名称,它引用的是对象本身。The this keyword is the name of a reference that refers to an object itself
- this关键字的常见用途:Common uses of the this keyword:
·引用类的“隐藏”数据字段。Reference a class’s “hidden” data fields
·调用重载构造函数 Calling Overloaded Constructor
>允许构造函数在构造函数的第一行调用同一类的另一个构造函数 .To enable a constructor to invoke another constructor of the same class as the first statement in the constructor.
4.类抽象和封装 Class Abstraction and Encapsulation
- 抽象:将类的实现细节与使用方式(API)分离。
Abstraction:separate class implementation from the use of the class (API)
- 封装:隐藏类的内部实现细节,仅通过公共接口(方法)暴露必要功能。
Encapsulation:Hiding the internal implementation details of a class and exposing only the necessary functionality through public interfaces (methods).
- 示例:
·Loan Class
·BMI Class
·The Course Class
·The StackOfIntegers Class
4.1 字符串类The String class
- 构造函数:String newString = new String(stringLiteral);
·由于字符串使用频繁,Java 提供了一种简写初始化器来创建字符串:
Since strings are used frequently, Java provides a shorthand initializer for creating a string: String message = "Welcome to Java";
- 性质:
·字符串是不可变的
·字符串池化(Interned Strings)
>字符串池化是一种方法,它只存储源代码中每个不同的编译时常量/显式字符串的一个副本,这些副本存放在字符串池(例如,s1 和 s3)中。String interning is a method of storing only one copy of each distinct compile-time constant/explicit string in the source code stored in a string intern pool (e.g., s1 and s3).
>如果我们使用 new操作符,那么会在堆中创建一个新的对象(例如,s2)if we use the new operator, then a new object is created in heap (e.g., s2).
- 字符串类的方法
·比较字符串(equals,compareTo)Compare strings (equals, compareTo)
·字符串长度、字符和组合字符串 String Length, Characters, and Combining Strings
·提取子字符串 Extracting Substrings
·在字符串中查找字符或子字符串Finding a Character or a Substring in a String
·匹配、替换和分割Matching, Replacing and Splitting
·按模式匹配、替换和分割 Matching, Replacing and Splitting by Patterns
·命令行参数Command-Line Parameters
4.1.1字符串比较
- +equals(s1: String): boolean
·如果此字符串等于字符串 s1,则返回 true。
Returns true if this string is equal to string s1.
- +equalsIgnoreCase(s1: String): boolean
·如果此字符串等于字符串 s1(不区分大小写),则返回 true。
Returns true if this string is equal to string s1 case-insensitive.
- +compareTo(s1: String): int
·返回一个大于0、等于0或小于0的整数,以指示此字符串是大于、等于还是小于 s1。Returns an integer greater than 0, equal to 0, or less than 0 to indicate whether this string is greater than, equal to, or less than s1.
- +compareToIgnoreCase(s1: String): int
·与 compareTo 相同,只是比较时不区分大小写。Same as compareTo except that the comparison is case insensitive
- +regionMatches(toffset: int, s1: String, offset: int, len: int): boolean
·如果此字符串的指定子区域与字符串 s1 中的指定子区域完全匹配,则返回 true。Returns true if the specified subregion of this string exactly matches the specified subregion in string s1.
- +regionMatches(ignoreCase: boolean, toffset: int, s1: String, offset: int, len: int): boolean
·与前述方法相同,只是你可以指定匹配是否区分大小写。 Same as the preceding method except that you can specify whether the match is case-sensitive.
- +startsWith(prefix: String): boolean
·如果此字符串以指定的前缀开头,则返回 true Returns true if this string starts with the specified prefix.
- +endsWith(suffix: String): boolean
·如果此字符串以指定的后缀结尾,则返回 true。Returns true if this string ends with the specified suffix.
4.1.2字符串长度、字符和组合字符串 String Length, Characters, and Combining Strings
- +length(): int
·返回此字符串中的字符数量。Returns the number of characters in this string.
- +charAt(index: int): char
·返回此字符串中指定索引处的字符。Returns the character at the specified index from this string.
- +concat(s1: String): String
·返回一个新字符串,该字符串将此字符串与字符串 s1 连接起来。 Returns a new string that concatenate this string with string s1.
4.1.3 提取子字符串 Extracting Substrings
- + subString(beginIndex: int): String
·返回从指定的 beginIndex开始直到字符串末尾的子字符串。Returns this string’s substring that begins with the character at the specified beginIndex and extends to the end of the string.
- + subString(beginIndex: int, endIndex: int): String
·返回从指定的 beginIndex开始直到索引 endIndex - 1处字符的子字符串。注意,endIndex 处的字符不是子字符串的一部分。Returns this string’s substring that begins at the specified beginIndex and extends to the character at index endIndex – 1. Note that the character at endIndex is not part of the substring.
eg:
4.1.4在字符串中查找字符或子字符串 Finding a Character or a Substring in a String
- +indexOf(ch: char): int
·返回字符串中字符 `ch` 第一次出现的索引。如果没有找到匹配项,则返回 -1。Returns the index of the first occurrence of ch in the string. Returns -1 if not matched.
- +indexOf(ch: char, fromIndex: int): int
·返回从 `fromIndex` 开始,字符串中字符 `ch` 第一次出现的索引。如果没有找到匹配项,则返回 -1。Returns the index of the first occurrence of ch after fromIndex in the string. Returns -1 if not matched.
- +indexOf(s: String): int
·返回字符串 `s` 在此字符串中第一次出现的索引。如果没有找到匹配项,则返回 -1。 Returns the index of the first occurrence of string s in this string. Returns -1 if not matched.
- +indexOf(s: String, fromIndex: int): int
·返回从 `fromIndex` 开始,字符串 `s` 在此字符串中第一次出现的索引。如果没有找到匹配项,则返回 -1。Returns the index of the first occurrence of string s in this string after fromIndex. Returns -1 if not matched.
- +lastIndexOf(ch: int): int
·返回字符串中字符 `ch` 最后一次出现的索引。如果没有找到匹配项,则返回 -1。Returns the index of the last occurrence of ch in the string. Returns -1 if not matched.
- +lastIndexOf(ch: int, fromIndex: int): int
·返回 `fromIndex` 之前,字符串中字符 `ch` 最后一次出现的索引。如果没有找到匹配项,则返回 -1。Returns the index of the last occurrence of ch before fromIndex in this string. Returns -1 if not matched.
- +lastIndexOf(s: String): int
·返回字符串 `s` 最后一次出现的索引。如果没有找到匹配项,则返回 -1。Returns the index of the last occurrence of string s. Returns -1 if not matched.
- +lastIndexOf(s: String, fromIndex: int): int
·返回 `fromIndex` 之前,字符串 `s` 最后一次出现的索引。如果没有找到匹配项,则返回 -1. Returns the index of the last occurrence of string s before fromIndex. Returns -1 if not matched.
eg:
4.1.5匹配、转换、替换和分割字符串 Converting, Replacing, and Splitting Strings
- +toLowerCase(): String
·返回一个新字符串,其中所有字符都转换为小写。Returns a new string with all characters converted to lowercase.
- +toUpperCase(): String
·返回一个新字符串,其中所有字符都转换为大写。Returns a new string with all characters converted to uppercase.
- +trim(): String
·返回一个新字符串,其中两侧的空白字符都被修剪掉了。Returns a new string with blank characters trimmed on both sides.
- +replace(oldChar: char, newChar: char): String
·返回一个新字符串,其中此字符串中的所有匹配字符都被新字符替换。Returns a new string that replaces all matching character in this string with the new character.
- +replaceFirst(oldString: String, newString: String): String
·返回一个新字符串,其中此字符串中的第一个匹配子字符串被新子字符串替换。 Returns a new string that replaces the first matching substring in this string with the new substring.
- +replaceAll(oldString: String, newString: String): String
·返回一个新字符串,其中此字符串中的所有匹配子字符串都被新子字符串替换。Returns a new string that replace all matching substrings in this string with the new substring.
- +split(delimiter: String): String[]
·返回一个字符串数组,这些字符串由分隔符分割而成的子字符串组成。Returns an array of strings consisting of the substrings split by the delimiter
- +matches(regex: String): boolean
·该方法用于判断一个字符串是否与给定的正则表达式匹配。The matches method tells whether or not a string matches a given regular expression.
·如果此字符串与模式匹配,则返回 true。Returns true if this string matches the pattern.
eg:
4.1.6按模式(正则表达式)匹配、替换和分割Matching, Replacing and Splitting by Patterns
- +matches(regex: String): boolean
·如果该字符串与给定的正则表达式匹配,则返回 true。Returns true if this string matches the pattern.
- +replaceAll(regex: String, replacement: String): String
·返回一个新字符串,将所有匹配的子字符串替换为指定的替换内容。Returns a new string that replaces all matching substrings with the replacement.
- +replaceFirst(regex: String, replacement: String): String
·返回一个新字符串,仅将第一个匹配的子字符串替换为指定的替换内容。Returns a new string that replaces the first matching substring with the replacement.
- +split(regex: String): String[]
·返回一个字符串数组,数组中的元素是根据匹配的模式进行分割后的子字符串。Returns an array of strings consisting of the substrings split by the matches.
- matches方法用于判断一个字符串是否符合指定的正则表达式。
The matches method tells whether or not a string matches a given regular expression.
- 示例:
·以下语句将字符串 "a+b$#c" 中的 $、+ 或 # 替换为字符串 "NNN",并返回一个新的字符串: String s = "a+b$#c".replaceAll("[$+#]", "NNN");
System.out.println(s);
>正则表达式`[$+#]表示一个字符类,匹配任意一个字符 $、+ 或 #。
>输出结果:aNNNbNNNNNNc
·"Java is fun".matches("Java.*") --> 返回结果为 `true`:
·社会保障号码格式:格式为 xxx-xx-xxxx,其中 x表示一个数字:
[\\d]{3}-[\\d]{2}-[\\d]{4}
[\\d]{3}:3 个数字 -:连字符 [\\d]{2}:2 个数字 [\\d]{4}:4 个数字
·偶数:以 0、2、4、6 或 8 结尾的任意长度数字串:
[\\d]*[02468]
[\\d]:0 个或多个数字 [02468]:以偶数字符结尾
·电话号码:格式为 (xxx) xxx-xxxx,其中 x 是数字,且第一个数字不能是 0:
\\([1-9][\\d]{2}\\) [\\d]{3}-[\\d]{4}
\\( 和 \\):匹配括号 [1-9][\\d]{2}:3 位区号,第一个数字非 0
[\\d]{3}-[\\d]{4}:电话号码的主干部分(3 位 + 4 位)
- 正则表达式
4.1.7命令行参数 Command-Line Parameters
- 我们可以通过命令行运行程序(eg:java TestMain arg0 arg1 arg2 ... argn)或者在 Eclipse IDE 的运行配置中设置参数。
- Java命令行计算器程序
4.2 StringBuilder/StringBuffer
- 定义:StringBuilder/StringBuffer 类是 String 类的替代品:可以在任何使用字符串的地方使用。The StringBuilder/StringBuffer classes are alternatives to the String class:can be used wherever a string is used
- 对比:
·StringBuffer vs StringBuilder
>StringBuffer是同步的,即线程安全的。这意味着两个线程不能同时调用 `StringBuffer` 的方法。StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously.
>StringBuilder是非同步的,即非线程安全的。这意味着两个线程可以同时调用 StringBuilder 的方法。StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.
·StringBuilder/StringBuffer vs String
>StringBuilder/StringBuffer 更加灵活 StringBuilder/StringBuffer is more flexible than String
>你可以向字符串缓冲区中添加、插入或追加新内容,而字符串对象的值一旦创建就是固定的。You can add, insert, or append new contents into a string buffer, whereas the value of a String object is fixed once the string is created
4.2.1构造函数
- +StringBuilder()
·构造一个容量为16的空的StringBuilder Constructs an empty string builder with capacity 16.
- +StringBuilder(capacity: int)
·构造一个具有指定容量的StringBuilder Constructs a string builder with the specified capacity.
- +StringBuilder(s: String)
·用指定的字符串构造一个StringBuilder Constructs a string builder with the specified string.
4.2.2修改Modifying
- +append(data: char[]): StringBuilder
·将字符数组追加到这个字符串构建器中。Appends a char array into this string builder.
- +append(data: char[], offset: int, len: int): StringBuilder
·将数据中的子数组追加到这个字符串构建器中。Appends a subarray in data into this string builder.
- +append(v: aPrimitiveType): StringBuilder
·将基本类型值作为字符串追加到这个构建器中。Appends a primitive type value as a string to this builder.
- +append(s: String): StringBuilder
·将字符串追加到这个字符串构建器中。Appends a string to this string builder.
- +delete(startIndex: int, endIndex: int): StringBuilder
·从起始索引到结束索引删除字符。Deletes characters from startIndex to endIndex.
- +deleteCharAt(index: int): StringBuilder
·删除指定索引处的字符。Deletes a character at the specified index.
- +insert(index: int, data: char[], offset: int, len: int): StringBuilder
·在指定索引处将数组中的数据子数组插入到构建器中。Inserts a subarray of the data in the array to the builder at the specified index.
- +insert(offset: int, data: char[]): StringBuilder
·在偏移位置插入数据到这个构建器中 Inserts data into this builder at the position offset.
- +insert(offset: int, b: aPrimitiveType): StringBuilder
·将转换为字符串的值插入到这个构建器中 Inserts a value converted to a string into this builder.
- +insert(offset: int, s: String): StringBuilder
·在偏移位置插入字符串到这个构建器中 Inserts a string into this builder at the position offset.
- +replace(startIndex: int, endIndex: int, s: String): StringBuilder
·用指定的字符串替换这个构建器中从起始索引到结束索引的字符。Replaces the characters in this builder from startIndex to endIndex with the specified string.
- +reverse(): StringBuilder
·反转构建器中的字符。Reverses the characters in the builder.
- +setCharAt(index: int, ch: char): void
·在这个构建器中指定索引处设置一个新的字符。Sets a new character at the specified index in this builder
4.2.3 toString、capacity、length、setLength 和 charAt 方法
- +toString(): String
·从字符串构建器返回一个字符串对象。Returns a string object from the string builder
- +capacity(): int
·返回此字符串构建器的容量。Returns the capacity of this string builder
- +charAt(index: int): char
·返回指定索引处的字符。Returns the character at the specified index.
- +length(): int
·返回此构建器中的字符数量。Returns the number of characters in this builder.
- +setLength(newLength: int): void
·在此构建器中设置一个新的长度。Sets a new length in this builder.
- +substring(startIndex: int): String
·返回从 startIndex 开始的子字符串。Returns a substring starting at startIndex.
- +substring(startIndex: int, endIndex: int): String
·返回从 startIndex 到 endIndex-1 的子字符串。Returns a substring from startIndex to endIndex-1
- +trimToSize(): void
·减少用于字符串构建器的存储大小。Reduces the storage size used for the string builder.
4.3 字符类The Character Class
- +Character(value: char)
·用字符值构造一个字符对象。Constructs a character object with char value
- +charValue(): char
·从此对象返回字符值。Returns the char value from this object
- +compareTo(anotherCharacter: Character): int
·将此字符与另一个字符进行比较。Compares this character with another
- +equals(anotherCharacter: Character): boolean
·如果此字符等于另一个字符,则返回 true。Returns true if this character equals to another
- +isDigit(ch: char): boolean
·如果指定的字符是数字,则返回 true。Returns true if the specified character is a digit
- +isLetter(ch: char): boolean
·如果指定的字符是字母,则返回 true。Returns true if the specified character is a letter
- +isLetterOrDigit(ch: char): boolean
·如果字符是字母或数字,则返回 true。Returns true if the character is a letter or a digit
- +isLowerCase(ch: char): boolean
·如果字符是小写字母,则返回 true。Returns true if the character is a lowercase letter
- +isUpperCase(ch: char): boolean
·如果字符是大写字母,则返回 true。Returns true if the character is an uppercase letter
- +toLowerCase(ch: char): char
·返回指定字符的小写形式。Returns the lowercase of the specified character
- +toUpperCase(ch: char): char
·返回指定字符的大写形式。Returns the uppercase of the specified character
4.4 设计类的方式Designing Classes
- 标准
·一致性:一个类应该描述单一实体。Coherence: A class should describe a single entity
·分离职责:具有过多职责的单一实体可以分解为多个类,以分离职责。Separating responsibilities: A single entity with too many responsibilities can be broken into several classes to separate responsibilities
·重用性:类的设计是为了重用!Reuse: Classes are designed for reuse!
- 遵循标准的Java编程风格和命名规范:Follow standard Java programming style and naming conventions:
·为类、数据字段和方法选择有意义的名称。Choose informative names for classes, data fields, and methods
·将数据声明放在构造函数之前,并将构造函数放在方法之前。Place the data declaration before the constructor, and place constructors before methods.
·尽可能提供一个公共的无参构造函数,并覆盖equals方法和toString方法(返回一个字符串)。Provide a public no-arg constructor and override the equals method and the toString method (returns a String) whenever possible