Skip to content

Arrays

Java for AP CS A Lesson 8 1:43 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
An array holds many values of one type under one name. 数组在一个名字底下,装很多个同一类型的值。
Each value sits at an index, and indexes start at zero. 每个值待在一个索引上,而索引从 0 开始。
So with three scores, scores zero is ninety and scores two is seventy. 所以三个分数里,scores 是 90,scores 是 70。
Look at the faded slot on the right: index three throws, because it does not exist. 看右边那个淡淡的格子: 索引 3 会抛异常,因为它根本不存在。
And the last index is always length minus one — that one fact is behind nearly every array error you will meet. 而最后一个索引永远是"长度减 1"—— 你以后碰到的几乎每一个数组错误,都出自这一条。
There are two ways to make one. 造一个数组有两种写法。
Write the values in braces and Java counts them for you. 把值写在花括号里,Java 会替你数好个数。
Or say how many you want with new, and you get an array of that size filled with zeros — or with false for booleans, and null for objects. 或者用 new 说明你要多少个, 你就得到那么大的一个数组,里面填满了 0—— boolean 数组填 false,对象数组填 null。
Either way, once it is made, an array's length can never change. 不管哪一种,数组一旦造好,它的长度就再也不能改了。
Two loops go through an array, and the difference is what each one hands you. 有两种循环可以走遍一个数组,区别在于它们交给你什么。
An indexed for gives you i, so you can use the position — and you need it if you want to write into the array. 带索引的 for 给你 i,所以你能用到位置—— 而且如果你要往数组里"写"东西,就必须用它。
An enhanced for hands you the value directly, which is shorter, but you cannot change the array through it. 增强 for 直接把值交给你,写起来更短, 但你没法通过它去改动数组。
Pick by whether you need the index. 按"你需不需要索引"来选。
Four things to take with you. 带走四点。
One: an array holds many values of one type. 第一:数组装的是同一类型的很多个值。
Two: indexes run from zero to length minus 1. 第二:索引从 0 到"长度减 1"。
Three: length is a field on an array — no brackets. 第三:length 是数组上的一个字段——不加括号。
Four: an enhanced for gives values, not indexes. 第四:增强 for 给的是值,不是索引。
Now work with arrays in the tasks below. 现在去下面的题里练一练数组。

Log in or create account

IGCSE, A-Level & AP