ArrayList<E>
12 methodsList 接口的可变数组实现。允许 null 和所有元素。
int length()将指定元素追加到列表末尾。
Returns
int
Example
java
"hello".length() // 5
"".length() // 0char charAt(int index)返回指定位置处的元素。抛出 IndexOutOfBoundsException。
Parameters
| Name | Type | Description |
|---|---|---|
| index | int | 从 0 开始的索引。 |
Returns
char
Example
java
"hello".charAt(1) // 'e'
"hello".charAt(0) // 'h'String substring(int beginIndex, int endIndex)替换指定位置处的元素。返回之前的元素。
Parameters
| Name | Type | Description |
|---|---|---|
| index | int | 从 0 开始的索引。 |
| element | int | 新元素。 |
Returns
String
Example
java
"hello".substring(1, 3) // "el"
"hello".substring(2) // "llo"int indexOf(String str)移除指定位置处的元素。返回被移除的元素。
Parameters
| Name | Type | Description |
|---|---|---|
| index | String | 从 0 开始的索引。 |
Returns
int
Example
java
"hello".indexOf("ll") // 2
"hello".indexOf("z") // -1String[] split(String regex)返回列表中的元素数量。
Parameters
| Name | Type | Description |
|---|---|---|
| regex | String | Delimiting regex. |
Returns
String[]
Example
java
"a,b,c".split(",") // ["a", "b", "c"]
"hello".split("") // ["h","e","l","l","o"]
"a-b--c".split("-") // ["a", "b", "", "c"]String trim()如果列表不包含任何元素则返回 true。
Returns
String
Example
java
" hi ".trim() // "hi"
"\n hello\n".trim() // "hello"String replace(CharSequence target, CharSequence replacement)如果列表包含指定元素则返回 true(使用 equals)。
Parameters
| Name | Type | Description |
|---|---|---|
| target | CharSequence | 要查找的元素。 |
| replacement | CharSequence | Replacement. |
Returns
String
Example
java
"a-b-c".replace("-", "_") // "a_b_c"
"hello".replace("l", "L") // "heLLo"boolean equals(Object anObject)返回 o 首次出现的索引,未找到则返回 -1。
Parameters
| Name | Type | Description |
|---|---|---|
| anObject | Object | 要查找的元素。 |
Returns
boolean
Example
java
"hello".equals("hello") // true
"hello".equals("Hello") // false (case-sensitive)
new String("x") == "x" // false (reference compare)
new String("x").equals("x") // trueint compareTo(String anotherString)移除列表中的所有元素。
Parameters
| Name | Type | Description |
|---|---|---|
| anotherString | String | String to compare. |
Returns
int
Example
java
"abc".compareTo("abd") // negative
"abc".compareTo("abc") // 0
"abd".compareTo("abc") // positiveString toUpperCase()返回一个数组,按正确顺序包含列表中的所有元素。
Returns
String
Example
java
"hello".toUpperCase() // "HELLO"
"café".toUpperCase() // "CAFÉ"String toLowerCase()Convert all characters to lower case using the default locale.
Returns
String
Example
java
"HELLO".toLowerCase() // "hello"
"CAFÉ".toLowerCase() // "café"boolean contains(CharSequence s)Return true if and only if this string contains the specified sequence of char values.
Parameters
| Name | Type | Description |
|---|---|---|
| s | CharSequence | Sequence to search for. |
Returns
boolean
Example
java
"hello world".contains("world") // true
"hello".contains("z") // false