ArrayList
Java for AP CS A Lesson 10 2:03 English narration · English + 中文 subtitles burned in
Chapters
Transcript
An array's length is frozen the moment you make it, and often you do not know how many things there will be.
数组的长度在你造出它的那一刻就冻住了, 而很多时候你根本不知道最后会有多少个东西。
That is what ArrayList is for.
ArrayList 就是为这个而生的。
Watch: names dot add of Cai, and the list simply grows.
看:names.add("Cai"),这个列表就这么长长了。
The array above it cannot do that at all.
上面那个数组根本做不到。
And size goes up on its own — you never manage it.
而且 size 是自己涨的——你从来不用去管它。
Five methods cover almost everything the exam asks.
五个方法几乎覆盖了考试要问的一切。
size, how many there are.
size,有多少个。
add, put one on the end.
add,往末尾放一个。
get of i, read position i.
get(i),读第 i 个位置。
set of i and a value, replace position i.
set(i, v),替换第 i 个位置。
And remove of i, take one out.
还有 remove(i),拿掉一个。
Notice the first one: size has brackets because it is a method, while an array's length has none because it is a field.
注意第一个:size 带括号,因为它是方法; 而数组的 length 不带括号,因为它是字段。
That catches people every year.
这一点每年都要绊倒一批人。
One behaviour matters more than the rest, so watch it closely.
有一个行为比其余的都重要,所以仔细看。
Remove index one, and the list does not leave a hole.
remove(1),列表并不会留下一个空洞。
Everything after the gap slides down one to close it.
缺口后面的所有东西都往下挪一位,把它补上。
Cai was at index two; now Cai is at index one, not two.
Cai 原来在索引 2;现在 Cai 在索引 1,不是 2。
Remember that — the next lesson is built on it.
把这一点记住——下一课就建立在它上面。
One more rule.
还有一条规则。
An ArrayList stores objects only, so you cannot write ArrayList of int — it will not compile.
ArrayList 只能装对象, 所以你不能写 ArrayList<int>——它编译不过。
Use Integer, the wrapper type, and Double for decimals.
要用 Integer,也就是包装类型,小数用 Double。
The good news is that adding a plain five still works: Java wraps it for you, and that is called autoboxing.
好消息是,直接 add 一个 5 照样能用: Java 会替你把它包起来,这叫自动装箱。
Four things to take with you.
带走四点。
One: an ArrayList grows and shrinks, and an array cannot.
第一:ArrayList 能增能缩,而数组不能。
Two: size has brackets and length does not.
第二:size 带括号,length 不带。
Three: remove shifts everything after it down one.
第三:remove 会把它后面的所有东西往下挪一位。
Four: it stores objects, so use Integer, not int.
第四:它装的是对象,所以用 Integer,不是 int。
Now use an ArrayList in the tasks below.
现在去下面的题里用一用 ArrayList。