跳到主要内容
学科

AP 计算机科学 A

AP 计算机科学 A 是一门 Java 课程,分为四个单元:使用对象与方法、选择与循环、类的创建、 数据集合。它相当于大学一年级第一学期的编程课程,不要求任何先修经验。

自由作答部分要在纸上手写,而这正是多数学生练习不足之处。在 IDE 里打字、让编辑器帮你纠正 语法,与在没有任何帮助的情况下写出一个完整且可编译的方法,是两种不同的能力。请先在纸上写, 再原样敲进去,看它能否运行。

数组、ArrayList 与二维数组占自由作答分数的很大比重,其中大多数错误是边界处的差一错误—— 因此请专门针对第一个和最后一个元素追踪你的循环。本站笔记按 College Board 的单元编排,每 单元一页;本站 /code 的 Java 课程可在浏览器中运行,你可以立刻执行每一个示例。

AP 计算机科学 A历年真题

训练全部词汇
  • 1

    使用对象与方法

    讲义 词汇表
    1.1

    算法、编程与编译器导论

    大纲
    Learning ObjectiveEssential Knowledge

    1.1.A
    Represent patterns and algorithms found in everyday life using written language or diagrams.

    • 1.1.A.1 Algorithms define step-by-step processes to follow when completing a task or solving a problem. These algorithms can be represented using written language or diagrams.
    • 1.1.A.2 Sequencing defines an order for when steps in a process are completed. Steps in a process are completed one at a time.

    1.1.B
    Explain the code compilation and execution process.

    • 1.1.B.1 Code can be written in any text editor; however, an integrated development environment (IDE) is often used to write programs because it provides tools for a programmer to write, compile, and run code.
    • 1.1.B.2 A compiler checks code for some errors. Errors detectable by the compiler need to be fixed before the program can be run.

    1.1.C
    Identify types of programming errors.

    • 1.1.C.1 A syntax error is a mistake in the program where the rules of the programming language are not followed. These errors are detected by the compiler.
    • 1.1.C.2 A logic error is a mistake in the algorithm or program that causes it to behave incorrectly or unexpectedly. These errors are detected by testing the program with specific data to see if it produces the expected outcome.
    • 1.1.C.3 A run-time error is a mistake in the program that occurs during the execution of a program. Run-time errors typically cause the program to terminate abnormally.
    • 1.1.C.4 An exception is a type of run-time error that occurs as a result of an unexpected error that was not detected by the compiler. It interrupts the normal flow of the program's execution.

    来源:美国大学理事会 AP 课程与考试说明

    一个算法(algorithm)是一个解决一个问题的有限的、逐步的程序。一个程序(program)用一门计算机能运行的语言表达一个算法。Java 是编译(compiled)的:编译器(compiler)把你的源代码翻译成字节码(bytecode),它由 Java 虚拟机(JVM)(Java Virtual Machine)运行。一个语法错误(syntax error)(破坏语法)被编译器捕捉;一个逻辑错误(logic error)(错误的结果)不被——程序运行但行为不当。

    一个编译器一次翻译整个程序;一个解释器逐行运行它
    一个编译器一次翻译整个程序;一个解释器逐行运行它
    词汇表 训练
    英文 中文 拼音
    algorithm 算法 suàn fǎ
    program 程序 chéng xù
    compiled 编译 biān yì
    compiler 编译器 biān yì qì
    syntax error 语法错误 yǔ fǎ cuò wù
    logic error 逻辑错误 luó jí cuò wù
    1.2

    变量与数据类型

    大纲
    Learning ObjectiveEssential Knowledge

    1.2.A
    Identify the most appropriate data type category for a particular specification.

    • 1.2.A.1 A data type is a set of values and a corresponding set of operations on those values. Data types can be categorized as either primitive or reference.
    • 1.2.A.2 The primitive data types used in this course define the set of values and corresponding operations on those values for numbers and Boolean values.
    • 1.2.A.3 A reference type is used to define objects that are not primitive types.

    1.2.B
    Develop code to declare variables to store numbers and Boolean values.

    • 1.2.B.1 The three primitive data types used in this course are int, double, and boolean. An int value is an integer. A double value is a real number. A boolean value is either true or false.
      • Exclusion statement: The other five primitive data types (long, short, byte, float, and char) are outside the scope of the AP Computer Science A course and exam.
    • 1.2.B.2 A variable is a storage location that holds a value, which can change while the program is running. Every variable has a name and an associated data type. A variable of a primitive type holds a primitive value from that type.

    来源:美国大学理事会 AP 课程与考试说明

    一个变量(variable)是一个存储一个固定类型(type)的值的命名的盒子。Java 的主要基本类型(primitive types)是 int(整数)、double(小数)和 boolean(true/false)。类型在先地声明:

    Java 的基本数据类型,每个存储一种不同的值
    Java 的基本数据类型,每个存储一种不同的值
    int score = 90;
    double price = 4.99;
    boolean passed = true;
    
    探索

    Explore how a variable holds one value at a time

    A variable is a named box that stores one value of a fixed type. Step through the lines and watch each box take its value; notice that reassigning score overwrites the old number rather than making a new box.

    词汇表 训练
    英文 中文 拼音
    variable 变量 biàn liàng
    type 类型 lèi xíng
    primitive types 基本类型 jī běn lèi xíng
    1.3

    表达式与输出

    大纲
    Learning ObjectiveEssential Knowledge

    1.3.A
    Develop code to generate output and determine the result that would be displayed.

    • 1.3.A.1 System.out.print and System.out.println display information on the computer display. System.out.println moves the cursor to a new line after the information has been displayed, while System.out.print does not.

    1.3.B
    Develop code to utilize string literals and determine the result of using string literals.

    • 1.3.B.1 A literal is the code representation of a fixed value.
    • 1.3.B.2 A string literal is a sequence of characters enclosed in double quotes.
    • 1.3.B.3 Escape sequences are special sequences of characters that can be included in a string. They start with a \ and have a special meaning in Java. Escape sequences used in this course include double quote \", backslash \\, and newline \n.

    1.3.C
    Develop code for arithmetic expressions and determine the result of these expressions.

    • 1.3.C.1 Arithmetic expressions, which consist of numeric values, variables, and operators, include expressions of type int and double.
    • 1.3.C.2 The arithmetic operators consist of addition +, subtraction -, multiplication *, division /, and remainder %. An arithmetic operation that uses two int values will evaluate to an int value. An arithmetic operation that uses at least one double value will evaluate to a double value.
      • Exclusion statement: Expressions that result in special double values (e.g., infinities and NaN) are outside the scope of the AP Computer Science A course and exam.
    • 1.3.C.3 When dividing numeric values that are both int values, the result is only the integer portion of the quotient. When dividing numeric values that use at least one double value, the result is the quotient.
    • 1.3.C.4 The remainder operator % is used to compute the remainder when one number a is divided by another number b.
      • Exclusion statement: The use of values less than 0 for a and the use of values less than or equal to 0 for b is outside the scope of the AP Computer Science A course and exam.
    • 1.3.C.5 Operators can be used to construct compound expressions. At compile time, numeric values are associated with operators according to operator precedence to determine how they are grouped. Parentheses can be used to modify operator precedence. Multiplication, division, and remainder have precedence over addition and subtraction. Operators with the same precedence are evaluated from left to right.
    • 1.3.C.6 An attempt to divide an integer by the integer zero will result in an ArithmeticException.
      • Exclusion statement: The use of dividing by zero when one numeric value is a double is outside the scope of the AP Computer Science A course and exam.

    来源:美国大学理事会 AP 课程与考试说明

    一个表达式(expression)组合值和运算符(operators)来计算一个结果:+ - * /%(取模(modulus),余数)。整数除法(integer division)截断:7 / 23,而 7 % 21运算符优先级(operator precedence)遵循数学(*/%+- 之前)。用以下打印:

    System.out.print("no newline");
    System.out.println("with newline");
    

    整数除以整数 0(像 7 / 0)是不允许的,在运行时以一个 ArithmeticException 崩溃。在一个字符串里,一个反斜杠标记一个转义序列(escape sequence):\" 打印一个双引号,\\ 一个单反斜杠,而 \n 开始一个新行——所以 System.out.println("She said \"hi\""); 打印 She said "hi"

    探索

    Explore the order of operations step by step

    Java applies *, /, % before + and -, working left to right. Watch each step and see why 2 + 3 * 4 is $14$, not $20$ — the multiplication happens first.

    词汇表 训练
    英文 中文 拼音
    expression 表达式 biǎo dá shì
    modulus 取模 qǔ mó
    escape sequence 转义序列 zhuǎn yì xù liè
    1.4

    赋值语句与输入

    大纲
    Learning ObjectiveEssential Knowledge

    1.4.A
    Develop code for assignment statements with expressions and determine the value that is stored in the variable as a result of these statements.

    • 1.4.A.1 Every variable must be assigned a value before it can be used in an expression. That value must be from a compatible data type. A variable is initialized the first time it is assigned a value. Reference types can be assigned a new object or null if there is no object. The literal null is a special value used to indicate that a reference is not associated with any object.
    • 1.4.A.2 The assignment operator = allows a program to initialize or change the value stored in a variable. The value of the expression on the right is stored in the variable on the left.
      • Exclusion statement: The use of assignment operators inside expressions (e.g., a = b = 4; or a[i += 5]) is outside the scope of the AP Computer Science A course and exam.
    • 1.4.A.3 During execution, an expression is evaluated to produce a single value. The value of an expression has a type based on the evaluation of the expression.

    1.4.B
    Develop code to read input.

    • 1.4.B.1 Input can come in a variety of forms, such as tactile, audio, visual, or text. The Scanner class is one way to obtain text input from the keyboard.
      • Exclusion statement: Any specific form of input from the user is outside the scope of the AP Computer Science A course and exam.

    来源:美国大学理事会 AP 课程与考试说明

    一个赋值(assignment)x = expr; 求右侧的值并把它存进左边的变量。用一个 Scanner 读输入:

    Scanner in = new Scanner(System.in);
    int age = in.nextInt();
    String name = in.next();
    
    词汇表 训练
    英文 中文 拼音
    assignment 赋值 fù zhí
    1.5

    类型转换与变量取值范围

    大纲
    Learning ObjectiveEssential Knowledge

    1.5.A
    Develop code to cast primitive values to different primitive types in arithmetic expressions and determine the value that is produced as a result.

    • 1.5.A.1 The casting operators (int) and (double) can be used to convert from a double value to an int value (or vice versa).
    • 1.5.A.2 Casting a double value to an int value causes the digits to the right of the decimal point to be truncated.
    • 1.5.A.3 Some code causes int values to be automatically cast (widened) to double values.
    • 1.5.A.4 Values of type double can be rounded to the nearest integer by (int)(x + 0.5) for non-negative numbers or (int)(x - 0.5) for negative numbers.

    1.5.B
    Describe conditions when an integer expression evaluates to a value out of range.

    • 1.5.B.1 The constant Integer.MAX_VALUE holds the value of the largest possible int value. The constant Integer.MIN_VALUE holds the value of the smallest possible int value.
    • 1.5.B.2 Integer values in Java are represented by values of type int, which are stored using a finite amount (4 bytes) of memory. Therefore, an int value must be in the range from Integer.MIN_VALUE to Integer.MAX_VALUE inclusive.
    • 1.5.B.3 If an expression would evaluate to an int value outside of the allowed range, an integer overflow occurs. The result is an int value in the allowed range but not necessarily the value expected.

    1.5.C
    Describe conditions that limit accuracy of expressions.

    • 1.5.C.1 Computers allot a specified amount of memory to store data based on the data type. If an expression would evaluate to a double that is more precise than can be stored in the allotted amount of memory, a round-off error occurs. The result will be rounded to the representable value. To avoid rounding errors that naturally occur, use int values.
      • Exclusion statement: Other special decimal data types that can be used to avoid rounding errors are outside the scope of the AP Computer Science A course and exam.

    来源:美国大学理事会 AP 课程与考试说明

    int 的范围、溢出与截断

    每个类型有一个固定的范围;一个 int 超过约 21 亿溢出。类型转换(casting)在类型之间转换。加宽(intdouble)是自动的;缩窄需要一个显式的转换,它截断(不舍入):

    double avg = (double) total / count;   // force real division
    int whole = (int) 3.9;                 // 3, truncated
    

    考试技能: 注意整数除法在期望一个小数时产生一个截断的结果——先把一个操作数转换成 double

    Worked example. 跟踪每个表达式:

    • 7 / 23(两个都是 int,所以除法截断);
    • 7.0 / 23.5(一个 double 迫使实数除法);
    • 7 % 21(余数);
    • (double) 7 / 23.5(转换比 / 结合得更紧,所以它是 7.0 / 2);
    • (double) (7 / 2)3.0(括号int 计算 7 / 2 = 3,然后加宽)。

    最后两个看起来相似但不同——转换的位置决定截断是否发生。

    探索

    Why int and double store numbers differently

    An int holds only whole numbers in a fixed range; a double stores a mantissa and an exponent, trading exactness for a huge range. Casting doubleint throws away the fraction, and a value past an int's range overflows.

    词汇表 训练
    英文 中文 拼音
    Casting 类型转换 lèi xíng zhuǎn huàn
    1.6

    复合赋值运算符

    大纲
    Learning ObjectiveEssential Knowledge

    1.6.A
    Develop code for assignment statements with compound assignment operators and determine the value that is stored in the variable as a result.

    • 1.6.A.1 Compound assignment operators +=, -=, *=, /=, and %= can be used in place of the assignment operator in numeric expressions. A compound assignment operator performs the indicated arithmetic operation between the value on the left and the value on the right and then assigns the result to the variable on the left.
    • 1.6.A.2 The post-increment operator ++ and post-decrement operator -- are used to add 1 or subtract 1 from the stored value of a numeric variable. The new value is assigned to the variable.
      • Exclusion statement: The use of increment and decrement operators in prefix form (e.g., ++x) is outside the scope of the AP Computer Science A course and exam. The use of increment and decrement operators inside other expressions (e.g., arr[x++]) is outside the scope of the AP Computer Science A course and exam.

    来源:美国大学理事会 AP 课程与考试说明

    简写把一个运算与赋值结合:x += 5 意味着 x = x + 5;同样 -=*=/=%=自增(increment)和自减(decrement)运算符 x++x-- 加或减一。

    1.7

    应用程序接口(API)与库

    大纲
    Learning ObjectiveEssential Knowledge

    1.7.A
    Identify the attributes and behaviors of a class found in the libraries contained in an API.

    • 1.7.A.1 Libraries are collections of classes. An application programming interface (API) specification informs the programmer how to use those classes. Documentation found in API specifications and libraries is essential to understanding the attributes and behaviors of a class defined by the API. A class defines a specific reference type. Classes in the APIs and libraries are grouped into packages. Existing classes and class libraries can be utilized to create objects.
    • 1.7.A.2 Attributes refer to the data related to the class and are stored in variables. Behaviors refer to what instances of the class can do (or what can be done with them) and are defined by methods.

    来源:美国大学理事会 AP 课程与考试说明

    一个 API(应用程序接口,Application Programming Interface)是你可以使用的类和方法的已发布列表。一个(library)是一个现成类的搜集(像 MathStringScanner)。你读 API 文档以学一个方法需要什么(它的参数)和返回什么,而不看它的内部代码——抽象(abstraction)的一个例子。

    词汇表 训练
    英文 中文 拼音
    library
    abstraction 抽象 chōu xiàng
    Interface 应用程序接口 yìng yòng chéng xù jiē kǒu
    1.8

    用注释编写文档

    大纲
    Learning ObjectiveEssential Knowledge

    1.8.A
    Describe the functionality and use of code through comments.

    • 1.8.A.1 Comments are written for both the original programmer and other programmers to understand the code and its functionality, but are ignored by the compiler and are not executed when the program is run. Three types of comments in Java include /* */, which generates a block of comments; //, which generates a comment on one line; and /** */, which are Javadoc comments and are used to create API documentation.
    • 1.8.A.2 A precondition is a condition that must be true just prior to the execution of a method in order for it to behave as expected. There is no expectation that the method will check to ensure preconditions are satisfied.
    • 1.8.A.3 A postcondition is a condition that must always be true after the execution of a method. Postconditions describe the outcome of the execution in terms of what is being returned or the current value of the attributes of an object.

    来源:美国大学理事会 AP 课程与考试说明

    注释(comments)被编译器忽略但向人类解释代码:// 用于单行、/* ... */ 用于一个块,而 /** ... */ 用于一个 Javadoc 注释,它记录一个方法的目的、参数和返回值。精确的前置条件(preconditions)和后置条件(postconditions)写在这里。

    词汇表 训练
    英文 中文 拼音
    Comments 注释 zhù shì
    1.9

    方法签名

    大纲
    Learning ObjectiveEssential Knowledge

    1.9.A
    Identify the correct method to call based on documentation and method signatures.

    • 1.9.A.1 A method is a named block of code that only runs when it is called. A block of code is any section of code that is enclosed in braces. Procedural abstraction allows a programmer to use a method by knowing what the method does even if they do not know how the method was written.
    • 1.9.A.2 A parameter is a variable declared in the header of a method or constructor and can be used inside the body of the method. This allows values or arguments to be passed and used by a method or constructor. A method signature for a method with parameters consists of the method name and the ordered list of parameter types. A method signature for a method without parameters consists of the method name and an empty parameter list.

    1.9.B
    Describe how to call methods.

    • 1.9.B.1 A void method does not have a return value and is therefore not called as part of an expression.
    • 1.9.B.2 A non-void method returns a value that is the same type as the return type in the header. To use the return value when calling a non-void method, it must be stored in a variable or used as part of an expression.
    • 1.9.B.3 An argument is a value that is passed into a method when the method is called. The arguments passed to a method must be compatible in number and order with the types identified in the parameter list of the method signature. When calling methods, arguments are passed using call by value. Call by value initializes the parameters with copies of the arguments.
    • 1.9.B.4 Methods are said to be overloaded when there are multiple methods with the same name but different signatures.
    • 1.9.B.5 A method call interrupts the sequential execution of statements, causing the program to first execute the statements in the method before continuing. Once the last statement in the method has been executed or a return statement is executed, the flow of control is returned to the point immediately following where the method was called.

    来源:美国大学理事会 AP 课程与考试说明

    一个方法签名(method signature)是一个方法的名字加它的参数类型,例如 nextInt()substring(int, int)。要调用一个方法你必须提供在数量、类型和顺序上匹配参数的实参(arguments)。完整的方法头也陈述返回类型(return type)——方法返回的值的类型(若没有则是 void)——但返回类型不是签名的一部分,这就是为什么两个方法不能仅凭返回类型不同来区分。

    词汇表 训练
    英文 中文 拼音
    method signature 方法签名 fāng fǎ qiān míng
    arguments 实参 shí cān
    1.10

    调用类方法

    大纲
    Learning ObjectiveEssential Knowledge

    1.10.A
    Develop code to call class methods and determine the result of those calls.

    • 1.10.A.1 Class methods are associated with the class, not instances of the class. Class methods include the keyword static in the header before the method name.
    • 1.10.A.2 Class methods are typically called using the class name along with the dot operator. When the method call occurs in the defining class, the use of the class name is optional in the call.

    来源:美国大学理事会 AP 课程与考试说明

    一个类(静态)方法(class (static) method)属于类本身,所以你在类名上调用它:ClassName.method(args)。不需要对象。

    探索

    Follow a class-method call on the stack

    Calling a class method like Math.max pushes a new frame onto the call stack; when the method returns a value, its frame pops and control goes back to the caller. Step through to watch the stack grow and shrink.

    词汇表 训练
    英文 中文 拼音
    class (static) method 类方法 lèi fāng fǎ
    class lèi
    1.11

    Math 类

    大纲
    Learning ObjectiveEssential Knowledge

    1.11.A
    Develop code to write expressions that incorporate calls to built-in mathematical libraries and determine the value that is produced as a result.

    • 1.11.A.1 The Math class is part of the java.lang package. Classes in the java.lang package are available by default.
    • 1.11.A.2 The Math class contains only class methods. The following Math class methods—including what they do and when they are used—are part of the Java Quick Reference:
      • static int abs(int x) returns the absolute value of an int value.
      • static double abs(double x) returns the absolute value of a double value.
      • static double pow(double base, double exponent) returns the value of the first parameter raised to the power of the second parameter.
      • static double sqrt(double x) returns the nonnegative square root of a double value.
      • static double random() returns a double value greater than or equal to 0.0 and less than 1.0.
    • 1.11.A.3 The values returned from Math.random() can be manipulated using arithmetic and casting operators to produce a random int or double in a defined range based on specified criteria. Each endpoint of the range can be inclusive, meaning the value is included, or exclusive, meaning the value is not included.

    来源:美国大学理事会 AP 课程与考试说明

    Math 类提供静态数学方法:Math.abs(x)Math.pow(base, exp)Math.sqrt(x),和 Math.random()($[0,1)$ 里的一个 double)。要得到一个从 0n-1 的随机整数:(int)(Math.random() * n)

    1.12

    对象:类的实例

    大纲
    Learning ObjectiveEssential Knowledge

    1.12.A
    Explain the relationship between a class and an object.

    • 1.12.A.1 An object is a specific instance of a class with defined attributes. A class is the formal implementation, or blueprint, of the attributes and behaviors of an object.
    • 1.12.A.2 A class hierarchy can be developed by putting common attributes and behaviors of related classes into a single class called a superclass. Classes that extend a superclass, called subclasses, can draw upon the existing attributes and behaviors of the superclass without replacing these in the code. This creates an inheritance relationship from the subclasses to the superclass.
      • Exclusion statement: Designing and implementing inheritance relationships are outside the scope of the AP Computer Science A course and exam.
    • 1.12.A.3 All classes in Java are subclasses of the Object class.

    1.12.B
    Develop code to declare variables to store reference types.

    • 1.12.B.1 A variable of a reference type holds an object reference, which can be thought of as the memory address of that object.

    来源:美国大学理事会 AP 课程与考试说明

    = 复制的是引用,不是对象

    一个(class)是一个蓝图;一个对象(object)是从它构建的一个具体的实例(instance)。一个类把数据(字段)与行为(方法)捆绑——面向对象编程(object-oriented programming)的核心。StringScannerArrayList 都是你实例化的类。

    类可以被组织成一个层级。一个父类(superclass)持有几个子类(subclasses)共享的属性和行为,这些子类 extend(扩展)它——一个继承关系(inheritance relationship)。Java 里每个类最终都是内置 Object 类的一个子类,这就是为什么每个对象已经有一个 toString 方法;写一个与父类方法有相同签名的子类方法就是方法重写(method overriding)。(设计你自己的继承超出本课程,但你要能识别这些词汇。)

    一个类图:私有属性和公有方法
    一个类图:私有属性和公有方法
    一个类是一个蓝图;每个对象是从它构建的一个实例
    一个类是一个蓝图;每个对象是从它构建的一个实例
    词汇表 训练
    英文 中文 拼音
    object 对象 duì xiàng
    instance 实例 shí lì
    object-oriented programming 面向对象编程 miàn xiàng duì xiàng biān chéng
    superclass 父类 fù lèi
    subclasses 子类 zi lèi
    inheritance relationship 继承关系 jì chéng guān xì
    method overriding 方法重写 fāng fǎ zhòng xiě
    reference 引用 yǐn yòng
    1.13

    对象的创建与存储(实例化)

    大纲
    Learning ObjectiveEssential Knowledge

    1.13.A
    Identify, using its signature, the correct constructor being called.

    • 1.13.A.1 A class contains constructors that are called to create objects. They have the same name as the class.
    • 1.13.A.2 A constructor signature consists of the constructor's name, which is the same as the class name, and the ordered list of parameter types. The parameter list, in the header of a constructor, lists the types of the values that are passed and their variable names.
    • 1.13.A.3 Constructors are said to be overloaded when there are multiple constructors with different signatures.

    1.13.B
    Develop code to declare variables of the correct types to hold object references.

    • 1.13.B.1 A variable of a reference type holds an object reference or, if there is no object, null.

    1.13.C
    Develop code to create an object by calling a constructor.

    • 1.13.C.1 An object is typically created using the keyword new followed by a call to one of the class's constructors.
    • 1.13.C.2 Parameters allow constructors to accept values to establish the initial values of the attributes of the object.
    • 1.13.C.3 A constructor argument is a value that is passed into a constructor when the constructor is called. The arguments passed to a constructor must be compatible in order and number with the types identified in the parameter list in the constructor signature. When calling constructors, arguments are passed using call by value. Call by value initializes the parameters with copies of the arguments.
    • 1.13.C.4 A constructor call interrupts the sequential execution of statements, causing the program to first execute the statements in the constructor before continuing. Once the last statement in the constructor has been executed, the flow of control is returned to the point immediately following where the constructor was called.

    来源:美国大学理事会 AP 课程与考试说明

    实例化(instantiation)用 new 关键字创建一个对象,它调用一个构造函数(constructor):

    Scanner in = new Scanner(System.in);
    String s = new String("hi");   // or just "hi"
    

    变量持有一个引用(reference)(对象的地址),不是对象本身。两个引用能指向同一个对象;用 == 比较它们比较地址,不是内容。

    一个引用也能指向空:特殊值 null(空值)意味着“不附着于任何对象”。在一个 null 引用上调用一个方法会在运行时以一个 NullPointerException 崩溃。通过用 ==/!= 测试并检查 null 来防范,这样 && 在方法运行前短路:if (s != null && s.length() > 0)

    一个基本变量直接持有它的值,一个引用持有指向对象的一个箭头
    一个基本变量直接持有它的值,一个引用持有指向对象的一个箭头
    词汇表 训练
    英文 中文 拼音
    Instantiation 实例化 shí lì huà
    constructor 构造函数 gòu zào hán shù
    null 空值 kōng zhí
    1.14

    调用实例方法

    大纲
    Learning ObjectiveEssential Knowledge

    1.14.A
    Develop code to call instance methods and determine the result of these calls.

    • 1.14.A.1 Instance methods are called on objects of the class. The dot operator is used along with the object name to call instance methods.
    • 1.14.A.2 A method call on a null reference will result in a NullPointerException.

    来源:美国大学理事会 AP 课程与考试说明

    一个实例方法(instance method)作用于一个特定的对象,所以你在对象引用上调用它:object.method(args)。例:in.nextInt()word.length()

    词汇表 训练
    英文 中文 拼音
    instance method 实例方法 shí lì fāng fǎ
    1.15

    字符串操作

    大纲
    Learning ObjectiveEssential Knowledge

    1.15.A
    Develop code to create string objects and determine the result of creating and combining strings.

    • 1.15.A.1 A String object represents a sequence of characters and can be created by using a string literal or by calling the String class constructor.
    • 1.15.A.2 The String class is part of the java.lang package. Classes in the java.lang package are available by default.
    • 1.15.A.3 A String object is immutable, meaning once a String object is created, its attributes cannot be changed. Methods called on a String object do not change the content of the String object.
    • 1.15.A.4 Two String objects can be concatenated together or combined using the + or += operator, resulting in a new String object. A primitive value can be concatenated with a String object. This causes the implicit conversion of the primitive value to a String object.
    • 1.15.A.5 A String object can be concatenated with any object, which implicitly calls the object's toString method (a behavior that is guaranteed to exist by the inheritance relationship every class has with the Object class). An object's toString method returns a string value representing the object. Subclasses of Object often override the toString method with class-specific implementation. Method overriding occurs when a public method in a subclass has the same method signature as a public method in the superclass, but the behavior of the method is specific to the subclass.
      • Exclusion statement: Overriding the toString method of a class is outside the scope of the AP Computer Science A course and exam.

    1.15.B
    Develop code to call methods on string objects and determine the result of calling these methods.

    • 1.15.B.1 A String object has index values from 0 to one less than the length of the string. Attempting to access indices outside this range will result in a StringIndexOutOfBoundsException.
    • 1.15.B.2 The following String methods—including what they do and when they are used—are part of the Java Quick Reference:
      • int length() returns the number of characters in a String object.
      • String substring(int from, int to) returns the substring beginning at index from and ending at index to - 1.
      • String substring(int from) returns substring(from, length()).
      • int indexOf(String str) returns the index of the first occurrence of str; returns -1 if not found.
      • boolean equals(Object other) returns true if this corresponds to the same sequence of characters as other; returns false otherwise.
      • int compareTo(String other) returns a value < 0 if this is less than other; returns zero if this is equal to other; returns a value > 0 if this is greater than other. Strings are ordered based upon the alphabet.
      • Exclusion statement: Using the equals method to compare one String object with an object of a type other than String is outside the scope of the AP Computer Science A course and exam.
    • 1.15.B.3 A string identical to the single element substring at position index can be created by calling substring(index, index + 1).

    来源:美国大学理事会 AP 课程与考试说明

    字符串不可变

    String 对象是不可变(immutable)的——方法返回一个字符串而不是改变原来的。关键方法(所有索引从 0 开始):

    s.length();            // number of characters
    s.substring(2, 5);     // chars at index 2,3,4 (5 excluded)
    s.indexOf("ab");       // first position, or -1
    s.equals(other);       // content comparison (never use == for Strings)
    s.compareTo(other);    // <0, 0, >0 by dictionary order
    

    考试技能: substring(a, b) 包括索引 a排除 b,而字符串比较必须用 .equals,不是 == ——两个最被考查的字符串陷阱。

    Worked example.String s = "COMPUTER";(索引 07)。那么 s.length()8;s.substring(0, 4)"COMP"(索引 0,1,2,3 ——索引 4 被排除);s.substring(4)"UTER"(从索引 4 到末尾);s.indexOf("PU")3;而 s.indexOf("X")-1(未找到)。数 substring 被排除的端点是单个最常见的失误。

    请求一个在 0length()-1 之外的索引(一个坏的 substringcharAt 参数,例如这里的 s.substring(0, 20))会以一个 StringIndexOutOfBoundsException 崩溃——数组索引错误的字符串表亲。

    字符串索引从 0 开始
    字符串索引从 0 开始
    探索

    Explore string indices and slicing

    Every character has an index, and the numbering starts at 0. Drag the start and end to see how substring(from, to) takes the characters from from up to — but not includingto.

    词汇表 训练
    英文 中文 拼音
    immutable 不可变 bù kě biàn
    1.15

    考试技巧

    • 逐行手工跟踪代码,在一张表里追踪每个变量的值——考试奖励仔细的跟踪而不是猜测。
    • 知道 Java 的基本类型以及整数除法截断($7/2$ 给出 $3$);用一个转换或一个 double 做实数除法。
    • 区分编译时错误(语法、类型)和运行时错误——知道有名字的那些:ArithmeticException(int ÷ 0)、NullPointerException(在 null 引用上的方法)、StringIndexOutOfBoundsException / ArrayIndexOutOfBoundsException——和逻辑错误(错误的输出)。
    • 遵循运算符优先级并在你使用每个变量之前初始化它。
    • 在自由回答上,写完整的、可编译的 Java ——返回正确的类型并精确匹配方法头。
  • 2

    选择与迭代

    讲义 词汇表
    2.1

    带选择与重复的算法

    大纲
    Learning ObjectiveEssential Knowledge

    2.1.A
    Represent patterns and algorithms that involve selection and repetition found in everyday life using written language or diagrams.

    • 2.1.A.1 The building blocks of algorithms include sequencing, selection, and repetition.
    • 2.1.A.2 Algorithms can contain selection, through decision making, and repetition, via looping.
    • 2.1.A.3 Selection occurs when a choice of how the execution of an algorithm will proceed is based on a true or false decision.
    • 2.1.A.4 Repetition is when a process repeats itself until a desired outcome is reached.
    • 2.1.A.5 The order in which sequencing, selection, and repetition are used contributes to the outcome of the algorithm.

    来源:美国大学理事会 AP 课程与考试说明

    算法由三种控制结构(control structures)构建:顺序(sequence)(按顺序的步骤)、选择(selection)(选择一条路径),和迭代(iteration)(重复步骤)。这个主题涵盖选择和迭代——让一个程序做决定和循环的工具。

    三种控制结构:顺序、选择和迭代
    三种控制结构:顺序、选择和迭代
    词汇表 训练
    英文 中文 拼音
    control structures 控制结构 kòng zhì jié gòu
    selection 选择 xuǎn zé
    iteration 迭代 dié dài
    2.2

    布尔表达式

    大纲
    Learning ObjectiveEssential Knowledge

    2.2.A
    Develop code to create Boolean expressions with relational operators and determine the result of these expressions.

    • 2.2.A.1 Values can be compared using the relational operators == and != to determine whether the values are the same. With primitive types, this compares the actual primitive values. With reference types, this compares the object references.
    • 2.2.A.2 Numeric values can be compared using the relational operators <, >, <=, and >= to determine the relationship between the values.
    • 2.2.A.3 An expression involving relational operators evaluates to a Boolean value.

    来源:美国大学理事会 AP 课程与考试说明

    逻辑门与半加器

    一个布尔表达式(boolean expression)求值为 truefalse,用关系运算符(relational operators):==(相等)、!=(不相等)、<><=>=。注意 == 比较基本值但对对象比较对象引用,所以对 String.equals

    三个运算符家族:算术、关系和逻辑
    三个运算符家族:算术、关系和逻辑
    探索

    Explore the AND truth table

    A Boolean expression evaluates to true or false. AND is true only when both operands are true; toggle the inputs to see all four cases.

    词汇表 训练
    英文 中文 拼音
    boolean expression 布尔表达式 bù ěr biǎo dá shì
    relational operators 关系运算符 guān xì yùn suàn fú
    2.3

    if 语句

    大纲
    Learning ObjectiveEssential Knowledge

    2.3.A
    Develop code to represent branching logical processes by using selection statements and determine the result of these processes.

    • 2.3.A.1 Selection statements change the sequential execution of statements.
    • 2.3.A.2 An if statement is a type of selection statement that affects the flow of control by executing different segments of code based on the value of a Boolean expression.
    • 2.3.A.3 A one-way selection (if statement) is used when there is a segment of code to execute under a certain condition. In this case, the body is executed only when the Boolean expression is true.
    • 2.3.A.4 A two-way selection (if-else statement) is used when there are two segments of code—one to be executed when the Boolean expression is true and another segment for when the Boolean expression is false. In this case, the body of the if is executed when the Boolean expression is true, and the body of the else is executed when the Boolean expression is false.

    来源:美国大学理事会 AP 课程与考试说明

    一个条件语句(if statement)只在它的条件为真时运行一个块;一个可选的 else 给出一个替代:

    if (score >= 60) {
        System.out.println("Pass");
    } else {
        System.out.println("Fail");
    }
    
    Traffic lights: selection chooses which branch runs, just as if statements choose code paths
    Traffic lights: selection chooses which branch runs, just as if statements choose code paths
    探索

    See which branch an if chooses

    An if statement runs its body only when the condition is true, otherwise it skips to else. Slide the score across the boundaries and watch the grade change.

    词汇表 训练
    英文 中文 拼音
    if statement 条件语句 tiáo jiàn yǔ jù
    2.4

    嵌套 if 语句

    大纲
    Learning ObjectiveEssential Knowledge

    2.4.A
    Develop code to represent nested branching logical processes and determine the result of these processes.

    • 2.4.A.1 Nested if statements consist of if, if-else, or if-else-if statements within if, if-else, or if-else-if statements.
    • 2.4.A.2 The Boolean expression of the inner nested if statement is evaluated only if the Boolean expression of the outer if statement evaluates to true.
    • 2.4.A.3 A multiway selection (if-else-if) is used when there are a series of expressions with different segments of code for each condition. Multiway selection is performed such that no more than one segment of code is executed based on the first expression that evaluates to true. If no expression evaluates to true and there is a trailing else statement, then the body of the else is executed.

    来源:美国大学理事会 AP 课程与考试说明

    把一个 if 放进另一个里面,或用 else if 链接,按顺序测试几个情况。只有第一个匹配的分支运行:

    if (g >= 90) grade = 'A';
    else if (g >= 80) grade = 'B';
    else grade = 'C';
    
    2.5

    复合布尔表达式

    大纲
    Learning ObjectiveEssential Knowledge

    2.5.A
    Develop code to represent compound Boolean expressions and determine the result of these expressions.

    • 2.5.A.1 Logical operators ! (not), && (and), and || (or) are used with Boolean expressions. The expression !a evaluates to true if a is false and evaluates to false otherwise. The expression a && b evaluates to true if both a and b are true and evaluates to false otherwise. The expression a || b evaluates to true if a is true, b is true, or both, and evaluates to false otherwise. The order of precedence for evaluating logical operators is ! (not), && (and), then || (or). An expression involving logical operators evaluates to a Boolean value.
    • 2.5.A.2 Short-circuit evaluation occurs when the result of a logical operation using && or || can be determined by evaluating only the first Boolean expression. In this case, the second Boolean expression is not evaluated.

    来源:美国大学理事会 AP 课程与考试说明

    短路求值

    逻辑运算符(logical operators)组合条件:&&(——两者都真)、||(——至少一个真)、!(——反转)。Java 用短路求值(short-circuit evaluation):&& 若左侧为假则停止,而 || 若左侧为真则停止——对防止错误有用,例如 if (n != 0 && total / n > 5)

    词汇表 训练
    英文 中文 拼音
    Logical operators 逻辑运算符 luó jí yùn suàn fú
    short-circuit evaluation 短路求值 duǎn lù qiú zhí
    2.6

    比较布尔表达式

    大纲
    Learning ObjectiveEssential Knowledge

    2.6.A
    Compare equivalent Boolean expressions.

    • 2.6.A.1 Two Boolean expressions are equivalent if they evaluate to the same value in all cases. Truth tables can be used to prove Boolean expressions are equivalent.
    • 2.6.A.2 De Morgan's law can be applied to Boolean expressions to create equivalent Boolean expressions. Under De Morgan's law, the Boolean expression !(a && b) is equivalent to !a || !b and the Boolean expression !(a || b) is equivalent to !a && !b.

    2.6.B
    Develop code to compare object references using Boolean expressions and determine the result of these expressions.

    • 2.6.B.1 Two different variables can hold references to the same object. Object references can be compared using == and !=.
    • 2.6.B.2 An object reference can be compared with null, using == or !=, to determine if the reference actually references an object.
    • 2.6.B.3 Classes often define their own equals method, which can be used to specify the criteria for equivalency for two objects of the class. The equivalency of two objects is most often determined using attributes from the two objects.
      • Exclusion statement: Overriding the equals method is outside the scope of the AP Computer Science A course and exam.

    来源:美国大学理事会 AP 课程与考试说明

    德摩根定律(De Morgan's laws)重写否定:!(a && b) 等于 !a || !b,而 !(a || b) 等于 !a && !b。两个布尔表达式等价,若它们对每个输入给出相同的结果——一张真值表证明它。以这种方式化简条件是一个常见的考试任务。

    词汇表 训练
    英文 中文 拼音
    De Morgan's laws 德摩根定律 dé mó gēn dìng lǜ
    2.7

    while 循环

    大纲
    Learning ObjectiveEssential Knowledge

    2.7.A
    Identify when an iterative process is required to achieve a desired result.

    • 2.7.A.1 Iteration is a form of repetition. Iteration statements change the flow of control by repeating a segment of code zero or more times as long as the Boolean expression controlling the loop evaluates to true.
    • 2.7.A.2 An infinite loop occurs when the Boolean expression in an iterative statement always evaluates to true.
    • 2.7.A.3 The loop body of an iterative statement will not execute if the Boolean expression initially evaluates to false.
    • 2.7.A.4 Off by one errors occur when the iteration statement loops one time too many or one time too few.

    2.7.B
    Develop code to represent iterative processes using while loops and determine the result of these processes.

    • 2.7.B.1 A while loop is a type of iterative statement. In while loops, the Boolean expression is evaluated before each iteration of the loop body, including the first. When the expression evaluates to true, the loop body is executed. This continues until the Boolean expression evaluates to false, whereupon the iteration terminates.

    来源:美国大学理事会 AP 课程与考试说明

    一个循环(while loop)在它的条件保持为真时当……时重复,在每一趟之前测试。你必须在里面改变某样东西以便循环最终停止,否则它变成一个无限循环(infinite loop):

    三种循环类型在条件被测试的地方不同
    三种循环类型在条件被测试的地方不同
    int i = 0;
    while (i < 5) {
        System.out.println(i);
        i++;
    }
    
    探索

    Trace a while loop

    A while loop repeats as long as its condition stays true, updating its variables each pass. Step through to see the sum of squares build up.

    词汇表 训练
    英文 中文 拼音
    while loop 循环 xún huán
    infinite loop 无限循环 wú xiàn xún huán
    2.8

    for 循环

    大纲
    Learning ObjectiveEssential Knowledge

    2.8.A
    Develop code to represent iterative processes using for loops and determine the result of these processes.

    • 2.8.A.1 A for loop is a type of iterative statement. There are three parts in a for loop header: the initialization, the Boolean expression, and the update.
    • 2.8.A.2 In a for loop, the initialization statement is only executed once before the first Boolean expression evaluation. The variable being initialized is referred to as a loop control variable. The Boolean expression is evaluated immediately after the loop control variable is initialized and then following each execution of the increment statement until it is false. In each iteration, the update is executed after the entire loop body is executed and before the Boolean expression is evaluated again.
    • 2.8.A.3 A for loop can be rewritten into an equivalent while loop (and vice versa).

    来源:美国大学理事会 AP 课程与考试说明

    一个 for 循环(for loop)把初始化、条件和更新打包进一行——当你知道次数时最好:

    for (int i = 0; i < n; i++) {
        // runs n times, i = 0..n-1
    }
    

    一个 for 和一个等价的 while 做相同的工作;能够在它们之间转换。

    An assembly line: loops repeat a process for every item, like for and while
    An assembly line: loops repeat a process for every item, like for and while
    探索

    Trace a for loop

    A for loop runs a fixed number of times, its counter stepping through a range. Watch the counter and running total advance one pass at a time.

    2.9

    实现选择与迭代算法

    大纲
    Learning ObjectiveEssential Knowledge

    2.9.A
    Develop code for standard and original algorithms (without data structures) and determine the result of these algorithms.

    • 2.9.A.1 There are standard algorithms to:
      • identify if an integer is or is not evenly divisible by another integer
      • identify the individual digits in an integer
      • determine the frequency with which a specific criterion is met
      • determine a minimum or maximum value
      • compute a sum or average

    来源:美国大学理事会 AP 课程与考试说明

    组合循环和条件来解决真实的问题——计数、求和、找一个最大值,或测试一个性质:

    int max = arr[0];
    for (int k = 1; k < arr.length; k++) {
        if (arr[k] > max) max = arr[k];
    }
    

    有两个整数模式,考试会直接考,它们用 %/。要一次一个地读出一个整数的各位数字,反复取 n % 10(最后一位)然后 n = n / 10(把它去掉)。要测试整除性,n % d == 0 表示 n 能被 d 整除。把它们和一个计数器结合起来,就能求出某个标准被满足的频率

    像一个连续总计、一个计数器,或一个标志(flag)(一个记录某事是否发生的布尔值)这样的标准模式贯穿整个课程重现。

    词汇表 训练
    英文 中文 拼音
    flag 标志 biāo zhì
    2.10

    实现字符串算法

    大纲
    Learning ObjectiveEssential Knowledge

    2.10.A
    Develop code for standard and original algorithms that involve strings and determine the result of these algorithms.

    • 2.10.A.1 There are standard string algorithms to:
      • find if one or more substrings have a particular property
      • determine the number of substrings that meet specific criteria
      • create a new string with the characters reversed

    来源:美国大学理事会 AP 课程与考试说明

    按索引循环遍历一个字符串以处理每个字符:

    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        // count vowels, reverse, check for a substring, ...
    }
    

    典型的任务:计数出现、构建一个反转或过滤的副本,或测试一个字符串是否包含另一个。

    2.11

    嵌套迭代

    大纲
    Learning ObjectiveEssential Knowledge

    2.11.A
    Develop code to represent nested iterative processes and determine the result of these processes.

    • 2.11.A.1 Nested iteration statements are iteration statements that appear in the body of another iteration statement. When a loop is nested inside another loop, the inner loop must complete all its iterations before the outer loop can continue to its next iteration.

    来源:美国大学理事会 AP 课程与考试说明

    一个嵌套循环(nested loop)把一个循环放进另一个里面;内层循环对外层的一趟完全完成。若外层运行 $n$ 次而内层 $m$ 次,主体运行 $n\times m$ 次——处理网格和比较所有对的基础。

    词汇表 训练
    英文 中文 拼音
    nested loop 嵌套循环 qiàn tào xún huán
    2.12

    非正式运行时间分析

    大纲
    Learning ObjectiveEssential Knowledge

    2.12.A
    Calculate statement execution counts and informal run-time comparison of iterative statements.

    • 2.12.A.1 A statement execution count indicates the number of times a statement is executed by the program. Statement execution counts are often calculated informally through tracing and analysis of the iterative statements.

    来源:美国大学理事会 AP 课程与考试说明

    大 O 增长率

    运行时间分析(run-time analysis)数一个算法随着输入大小 $n$ 增长取多少基本步骤。数最内层语句的执行:一个遍历 $n$ 个项的单一循环是线性的($n$ 步);两个遍历 $n$ 的嵌套循环是二次的($n^2$)。这种非正式的计数让你能比较两个算法的效率。

    运行时间如何随元素数量 n 增长
    运行时间如何随元素数量 n 增长

    考试技能: 对于一个嵌套循环,能够以循环边界陈述内层语句运行多少次——一个频繁的选择题。

    Worked example. 这个打印多少个星?

    for (int i = 0; i < 4; i++)
        for (int j = 0; j < i; j++)
            System.out.print("*");
    

    内层循环对每个外层 i 运行 i 次:0 + 1 + 2 + 3 = 6 个星。当内层边界是外层变量时,总数是三角和 $0+1+\dots+(n-1)=\dfrac{n(n-1)}{2}$ ——这里 $\dfrac{4\times3}{2}=6$ ——不是一个矩形嵌套循环的完整 $n^2=16$

    探索

    Compare how algorithms scale

    Run-time describes how the number of steps grows with the input size $n$. Increase $n$ and watch a linear $O(n)$ pull far ahead of a quadratic $O(n^2)$.

    词汇表 训练
    英文 中文 拼音
    Run-time analysis 运行时间分析 yùn xíng shí jiān fēn xī
    2.12

    考试技巧

    • 把边界条件搞对:有意地用 < vs <=,并注意每个循环的第一次和最后一次迭代(差一是经典的 bug)。
    • &&||! 构建复合条件并记住短路求值(把 null 检查放在先)。
    • 通过数内层主体总共运行多少次来跟踪嵌套循环。
    • 选择正确的结构——if/else if 用于范围、一个循环用于重复——并通过更新循环变量避免一个无限循环。
    • 当你化简或否定一个布尔条件时应用德摩根定律
  • 3

    类的创建

    讲义 词汇表
    3.1

    抽象与程序设计

    大纲
    Learning ObjectiveEssential Knowledge

    3.1.A
    Represent the design of a program by using natural language or creating diagrams that indicate the classes in the program and the data and procedural abstractions found in each class by including all attributes and behaviors.

    • 3.1.A.1 Abstraction is the process of reducing complexity by focusing on the main idea. By hiding details irrelevant to the question at hand and bringing together related and useful details, abstraction reduces complexity and allows one to focus on the idea.
    • 3.1.A.2 Data abstraction provides a separation between the abstract properties of a data type and the concrete details of its representation. Data abstraction manages complexity by giving data a name without referencing the specific details of the representation. Data can take the form of a single variable or a collection of data, such as in a class or a set of data.
    • 3.1.A.3 An attribute is a type of data abstraction that is defined in a class outside any method or constructor. An instance variable is an attribute whose value is unique to each instance of the class. A class variable is an attribute shared by all instances of the class.
    • 3.1.A.4 Procedural abstraction provides a name for a process and allows a method to be used only knowing what it does, not how it does it. Through method decomposition, a programmer breaks down larger behaviors of the class into smaller behaviors by creating methods to represent each individual smaller behavior. A procedural abstraction may extract shared features to generalize functionality instead of duplicating code. This allows for code reuse, which helps manage complexity.
    • 3.1.A.5 Using parameters allows procedures to be generalized, enabling the procedures to be reused with a range of input values or arguments.
    • 3.1.A.6 Using procedural abstraction in a program allows programmers to change the internals of a method (to make it faster, more efficient, use less storage, etc.) without needing to notify method users of the change as long as the method signature and what the method does is preserved.
    • 3.1.A.7 Prior to implementing a class, it is helpful to take time to design each class including its attributes and behaviors. This design can be represented using natural language or diagrams.

    来源:美国大学理事会 AP 课程与考试说明

    抽象(abstraction)意味着把细节隐藏在一个简单的接口之后——你使用一个 String 而不知道它如何存储字符。好的设计把一个问题分解成类,每个负责一个思想。这个主题是关于写你自己的类。

    把一个程序分解成模块和子模块
    把一个程序分解成模块和子模块
    词汇表 训练
    英文 中文 拼音
    Abstraction 抽象 chōu xiàng
    3.2

    程序设计的影响

    大纲
    Learning ObjectiveEssential Knowledge

    3.2.A
    Explain the social and ethical implications of computing systems.

    • 3.2.A.1 System reliability refers to the program being able to perform its tasks as expected under stated conditions without failure. Programmers should make an effort to maximize system reliability by testing the program with a variety of conditions.
    • 3.2.A.2 The creation of programs has impacts on society, the economy, and culture. These impacts can be both beneficial and harmful. Programs meant to fill a need or solve a problem can have unintended harmful effects beyond their intended use.
    • 3.2.A.3 Legal issues and intellectual property concerns arise when creating programs. Programmers often reuse code written by others and published as open source and free to use. Incorporation of code that is not published as open source requires the programmer to obtain permission and often purchase the code before integrating it into their program.

    来源:美国大学理事会 AP 课程与考试说明

    设计选择影响代码是否正确、可读和可重用。封装(encapsulation)——保持数据私有并只通过方法暴露它——保护一个对象的状态免于误用,并让你在不破坏类的用户的情况下改变里面。深思熟虑的命名、单一目的的方法和测试减少 bug。

    设计还承担着代码之外的责任。系统可靠性(system reliability) - 一个程序按预期完成任务、不出故障 - 是程序员应当通过精心的设计和测试去最大化的。程序对社会、经济和文化有真实的影响,这些影响既可以有益也可以有害。而且创造程序会引发法律和知识产权(intellectual property)方面的顾虑:程序员常常重用作为开源(open source)发布、可免费使用的代码,但必须尊重它的许可证并给出署名,而不是把他人的成果当作自己的来抄。

    词汇表 训练
    英文 中文 拼音
    Encapsulation 封装 fēng zhuāng
    System reliability 系统可靠性 xì tǒng kě kào xìng
    legal and intellectual-property 知识产权 zhī shí chǎn quán
    open source 开源 kāi yuán
    3.3

    类的结构剖析

    大纲
    Learning ObjectiveEssential Knowledge

    3.3.A
    Develop code to designate access and visibility constraints to classes, data, constructors, and methods.

    • 3.3.A.1 Data encapsulation is a technique in which the implementation details of a class are kept hidden from external classes. The keywords public and private affect the access of classes, data, constructors, and methods. The keyword private restricts access to the declaring class, while the keyword public allows access from classes outside the declaring class.
    • 3.3.A.2 In this course, classes are always designated public and are declared with the keyword class.
    • 3.3.A.3 In this course, constructors are always designated public.
    • 3.3.A.4 Instance variables belong to the object, and each object has its own copy of the variable.
    • 3.3.A.5 Access to attributes should be kept internal to the class in order to accomplish encapsulation. Therefore, it is good programming practice to designate the instance variables for these attributes as private unless the class specification states otherwise.
    • 3.3.A.6 Access to behaviors can be internal or external to the class. Methods designated as public can be accessed internally or externally to a class, whereas methods designated as private can only be accessed internally to the class.

    来源:美国大学理事会 AP 课程与考试说明

    一个类有三个部分:实例变量(instance variables)(字段——对象的数据)、构造函数(constructors)(构建对象),和方法(methods)(行为)。字段通常是 private;方法通常是 public:

    一个类图:私有属性和公有方法
    一个类图:私有属性和公有方法
    public class Student {
        private String name;      // instance variable
        private int score;
    
        public Student(String n, int s) {   // constructor
            name = n;
            score = s;
        }
        public int getScore() { return score; }   // accessor
    }
    
    A blueprint: a class is a template that defines how objects of that type are built
    A blueprint: a class is a template that defines how objects of that type are built
    探索

    See an object's fields as boxes

    A class groups related data (its fields) and methods. Each object gets its own set of field boxes; assigning to one changes that object only.

    词汇表 训练
    英文 中文 拼音
    instance variables 实例变量 shí lì biàn liàng
    constructor 构造函数 gòu zào hán shù
    accessor (getter) 访问器 fǎng wèn qì
    3.4

    构造方法

    大纲
    Learning ObjectiveEssential Knowledge

    3.4.A
    Develop code to declare instance variables for the attributes to be initialized in the body of the constructors of a class.

    • 3.4.A.1 An object's state refers to its attributes and their values at a given time and is defined by instance variables belonging to the object. This defines a has-a relationship between the object and its instance variables.
    • 3.4.A.2 A constructor is used to set the initial state of an object, which should include initial values for all instance variables. When a constructor is called, memory is allocated for the object and the associated object reference is returned. Constructor parameters, if specified, provide data to initialize instance variables.
    • 3.4.A.3 When a mutable object is a constructor parameter, the instance variable should be initialized with a copy of the referenced object. In this way, the instance variable does not hold a reference to the original object, and methods are prevented from modifying the state of the original object.
    • 3.4.A.4 When no constructor is written, Java provides a no-parameter constructor, and the instance variables are set to default values according to the data type of the attribute. This constructor is called the default constructor.
    • 3.4.A.5 The default value for an attribute of type int is 0. The default value of an attribute of type double is 0.0. The default value of an attribute of type boolean is false. The default value of a reference type is null.

    来源:美国大学理事会 AP 课程与考试说明

    一个构造函数(constructor)有与类相同的名字且没有返回类型。它在你写 new 时运行,而它的工作是初始化字段。一个类能有几个带不同参数列表的构造函数(重载(overloading));一个无参数构造函数设置默认值。

    词汇表 训练
    英文 中文 拼音
    overloading 重载 zhòng zài
    3.5

    方法:如何编写

    大纲
    Learning ObjectiveEssential Knowledge

    3.5.A
    Develop code to define behaviors of an object through methods written in a class using primitive values and determine the result of calling these methods.

    • 3.5.A.1 A void method does not return a value. Its header contains the keyword void before the method name.
    • 3.5.A.2 A non-void method returns a single value. Its header includes the return type in place of the keyword void.
    • 3.5.A.3 In non-void methods, a return expression compatible with the return type is evaluated, and the value is returned. This is referred to as return by value.
    • 3.5.A.4 The return keyword is used to return the flow of control to the point where the method or constructor was called. Any code that is sequentially after a return statement will never be executed. Executing a return statement inside a selection or iteration statement will halt the statement and exit the method or constructor.
    • 3.5.A.5 An accessor method allows objects of other classes to obtain a copy of the value of instance variables or class variables. An accessor method is a non-void method.
    • 3.5.A.6 A mutator (modifier) method is a method that changes the values of the instance variables or class variables. A mutator method is often a void method.
    • 3.5.A.7 Methods with parameters receive values through those parameters and use those values in accomplishing the method's task.
    • 3.5.A.8 When an argument is a primitive value, the parameter is initialized with a copy of that value. Changes to the parameter have no effect on the corresponding argument.

    来源:美国大学理事会 AP 课程与考试说明

    一个方法有一个签名、一个返回类型和一个主体。一个访问器(getter)(accessor)返回信息而不改变对象;一个修改器(setter)(mutator)改变一个字段。一个返回一个值的方法必须在每条路径上有一个正确类型的 return;一个 void 方法什么都不返回。

    public void setScore(int s) { score = s; }   // mutator
    public String toString() { return name + ": " + score; }
    
    探索

    Follow a method call and its return

    Calling a method pushes a frame with its parameters; when it hits return, the frame pops and the value goes back to the caller.

    词汇表 训练
    英文 中文 拼音
    mutator (setter) 修改器 xiū gǎi qì
    3.6

    方法:传递与返回对象引用

    大纲
    Learning ObjectiveEssential Knowledge

    3.6.A
    Develop code to define behaviors of an object through methods written in a class using object references and determine the result of calling these methods.

    • 3.6.A.1 When an argument is an object reference, the parameter is initialized with a copy of that reference; it does not create a new independent copy of the object. If the parameter refers to a mutable object, the method or constructor can use this reference to alter the state of the object. It is good programming practice to not modify mutable objects that are passed as parameters unless required in the specification.
    • 3.6.A.2 When the return expression evaluates to an object reference, the reference is returned, not a reference to a new copy of the object.
    • 3.6.A.3 Methods cannot access the private data and methods of a parameter that holds a reference to an object unless the parameter is the same type as the method's enclosing class.

    来源:美国大学理事会 AP 课程与考试说明

    = 复制的是引用,不是对象

    当你把一个对象传给一个方法时,Java 复制引用,所以方法作用于同一个对象——对它字段的变化对调用者可见。(基本类型按值复制,所以对它们的变化不可见。)一个方法也能返回一个对象的引用。因为一个 String 是不可变的,传一个是安全的;传一个可变的对象让一个方法能改变它。

    Java 按值传递:方法得到一个副本;真正的按引用传递(Java 没有)会让它重新赋值调用者的变量
    Java 总是按值传递(左):方法得到引用的一个副本。真正的按引用传递(右)——Java 没有——会让一个方法重新赋值调用者自己的变量。

    考试技能: 知道在一个方法里面改变一个对象的字段影响原来的,但重新赋值参数(param = new...)不影响调用者。

    Worked example. 假设 s 是一个分数为 50Student,而我们调用 tweak(s):

    public static void tweak(Student a) {
        a.setScore(100);          // (1) mutates the shared object
        a = new Student("Z", 0);  // (2) repoints the local copy only
        a.setScore(5);            // (3) changes only the new local object
    }
    

    第 (1) 行改变 s 指向的对象,所以调用者现在看到 100。第 (2) 行使方法自己的引用副本指向一个新的对象——调用者的 s 不受影响——而第 (3) 行只影响那个新对象。调用之后,s.getScore()100:改变留住了,重新赋值没有。

    3.7

    类变量与类方法

    大纲
    Learning ObjectiveEssential Knowledge

    3.7.A
    Develop code to define behaviors of a class through class methods.

    • 3.7.A.1 Class methods cannot access or change the values of instance variables or call instance methods without being passed an instance of the class via a parameter.
    • 3.7.A.2 Class methods can access or change the values of class variables and can call other class methods.

    3.7.B
    Develop code to declare the class variables that belong to the class.

    • 3.7.B.1 Class variables belong to the class, with all objects of a class sharing a single copy of the class variable. Class variables are designated with the static keyword before the variable type.
    • 3.7.B.2 Class variables that are designated public are accessed outside of the class by using the class name and the dot operator, since they are associated with a class, not objects of a class.
    • 3.7.B.3 When a variable is declared final, its value cannot be modified.

    来源:美国大学理事会 AP 课程与考试说明

    静态成员与实例成员

    一个静态(类)变量(static (class) variable),标记 static,被类的所有对象共享——总共一个副本(例如一个存在多少对象的计数器)。一个静态方法属于类而不能直接使用实例字段。按类名访问它们:Student.getCount()

    词汇表 训练
    英文 中文 拼音
    static (class) variable 类变量 lèi biàn liàng
    3.8

    作用域与访问权限

    大纲
    Learning ObjectiveEssential Knowledge

    3.8.A
    Explain where variables can be used in the code.

    • 3.8.A.1 Local variables are variables declared in the headers or bodies of blocks of code. Local variables can only be accessed in the block in which they are declared. Since constructors and methods are blocks of code, parameters to constructors or methods are also considered local variables. These variables may only be used within the constructor or method and cannot be declared to be public or private.
    • 3.8.A.2 When there is a local variable or parameter with the same name as an instance variable, the variable name will refer to the local variable instead of the instance variable within the body of the constructor or method.

    来源:美国大学理事会 AP 课程与考试说明

    作用域(scope)是一个名字可见的地方。一个在一个方法里声明的局部变量(local variable)只在它里面存在;一个参数(parameter)只在它的方法里存在;一个实例变量(instance variable)在整个对象里可见。访问修饰符控制跨类的可见性:private(只这个类)与 public(任何地方)。局部变量遮蔽(shadow)同名的字段——一个 bug 的来源。

    一个全局变量处处可见;一个局部变量只在它的块里面
    一个全局变量处处可见;一个局部变量只在它的块里面
    词汇表 训练
    英文 中文 拼音
    Scope 作用域 zuò yòng yù
    3.9

    this 关键字

    大纲
    Learning ObjectiveEssential Knowledge

    3.9.A
    Develop code for expressions that are self-referencing and determine the result of these expressions.

    • 3.9.A.1 Within an instance method or a constructor, the keyword this acts as a special variable that holds a reference to the current object—the object whose method or constructor is being called.
    • 3.9.A.2 The keyword this can be used to pass the current object as an argument in a method call.
    • 3.9.A.3 Class methods do not have a this reference.

    来源:美国大学理事会 AP 课程与考试说明

    this 是对当前对象的一个引用。用它来把一个字段与一个同名的参数区分开,或调用同一对象的另一个方法:

    public Student(String name, int score) {
        this.name = name;      // this.name is the field; name is the parameter
        this.score = score;
    }
    

    考试技能: 当一个构造函数或 setter 的参数与一个字段同名时,你必须this.field = param ——没有 this,赋值什么有用的都不做。

    3.9

    考试技巧

    • 用方法和类设计:把数据封装为 private 字段并通过公有方法暴露行为。
    • 知道一个对象和它的之间的差别,以及对象按值传递——参数得到引用的一个副本,所以一个方法能改变对象的状态,但重新赋值参数不影响调用者(Java 没有按引用传递)。
    • 安全地遍历数组和 ArrayList ——大小是 length vs .size(),而在一个循环期间移除会移动索引。
    • 跟踪一个递归方法以确定它的结果:先找到基本情况,然后沿着每次递归调用到它的返回值(写递归代码不在考试范围内)。
    • 认识继承词汇——超类、子类、方法重写,以及每个类都是 Object 的子类(设计和实现继承不在考试范围内)。
  • 4

    数据集合

    讲义 词汇表
    4.1

    数据采集的伦理与社会问题

    大纲
    Learning ObjectiveEssential Knowledge

    4.1.A
    Explain the risks to privacy from collecting and storing personal data on computer systems.

    • 4.1.A.1 When using a computer, personal privacy is at risk. When developing new programs, programmers should attempt to safeguard the personal privacy of the user.

    4.1.B
    Explain the importance of recognizing data quality and potential issues when using a data set.

    • 4.1.B.1 Algorithmic bias describes systemic and repeated errors in a program that create unfair outcomes for a specific group of users.
    • 4.1.B.2 Programmers should be aware of the data set collection method and the potential for bias when using this method before using the data to extrapolate new information or drawing conclusions.
    • 4.1.B.3 Some data sets are incomplete or contain inaccurate data. Using such data in the development or use of a program can cause the program to work incorrectly or inefficiently.

    4.1.C
    Identify an appropriate data set to use in order to solve a problem or answer a specific question.

    • 4.1.C.1 Contents of a data set might be related to a specific question or topic and might not be appropriate to give correct answers or extrapolate information for a different question or topic.

    来源:美国大学理事会 AP 课程与考试说明

    收集数据的程序提出隐私(privacy)和同意(consent)的问题。只收集需要的、保护它,并对它的使用诚实。数据能携带偏见(bias),若它不公平地代表每个人,导致不公平的结果——一个随着存储信息而来的责任。

    词汇表 训练
    英文 中文 拼音
    privacy 隐私 yǐn sī
    consent 同意 tóng yì
    bias 偏见 piān jiàn
    4.2

    使用数据集导论

    大纲
    Learning ObjectiveEssential Knowledge

    4.2.A
    Represent patterns and algorithms that involve data sets found in everyday life using written language or diagrams.

    • 4.2.A.1 A data set is a collection of specific pieces of information or data.
    • 4.2.A.2 Data sets can be manipulated and analyzed to solve a problem or answer a question. When analyzing data sets, values within the set are accessed and utilized one at a time and then processed according to the desired outcome.
    • 4.2.A.3 Data can be represented in a diagram by using a chart or table. This visual can be used to plan the algorithm that will be used to manipulate the data.

    来源:美国大学理事会 AP 课程与考试说明

    一个单一的变量持有一个值;真实的问题需要存储许多相关的值——一个班级名册、像素、传感器读数。一个数据结构(data structure)组织一个搜集,以便我们能高效地存储、找到和处理项。AP 课程用三个:数组(array)、ArrayList,和 2D 数组

    词汇表 训练
    英文 中文 拼音
    data structure 数据结构 shù jù jié gòu
    array 数组 shù zǔ
    4.3

    数组的创建与访问

    大纲
    Learning ObjectiveEssential Knowledge

    4.3.A
    Develop code used to represent collections of related data using one-dimensional (1D) array objects.

    • 4.3.A.1 An array stores multiple values of the same type. The values can be either primitive values or object references.
    • 4.3.A.2 The length of an array is established at the time of creation and cannot be changed. The length of an array can be accessed through the length attribute.
    • 4.3.A.3 When an array is created using the keyword new, all of its elements are initialized to the default values for the element data type. The default value for int is 0, for double is 0.0, for boolean is false, and for a reference type is null.
    • 4.3.A.4 Initializer lists can be used to create and initialize arrays.
    • 4.3.A.5 Square brackets [ ] are used to access and modify an element in a 1D array using an index.
    • 4.3.A.6 The valid index values for an array are 0 through one less than the length of the array, inclusive. Using an index value outside of this range will result in an ArrayIndexOutOfBoundsException.

    来源:美国大学理事会 AP 课程与考试说明

    一个数组(array)是一个固定大小的、有序的相同类型值的搜集。索引从 0length - 1:

    一个一维数组(一个列表),带它的索引和边界
    一个一维数组(一个列表),带它的索引和边界
    int[] nums = new int[5];        // five zeros
    int[] vals = {3, 1, 4, 1, 5};   // initialized
    int first = vals[0];            // 3
    int n = vals.length;            // 5 (a field, not a method)
    

    访问 0..length-1 之外的一个索引抛出一个 ArrayIndexOutOfBoundsException

    4.4

    数组遍历

    大纲
    Learning ObjectiveEssential Knowledge

    4.4.A
    Develop code used to traverse the elements in a 1D array and determine the result of these traversals.

    • 4.4.A.1 Traversing an array is when repetition statements are used to access all or an ordered sequence of elements in an array.
    • 4.4.A.2 Traversing an array with an indexed for loop or while loop requires elements to be accessed using their indices.
    • 4.4.A.3 An enhanced for loop header includes a variable, referred to as the enhanced for loop variable. For each iteration of the enhanced for loop, the enhanced for loop variable is assigned a copy of an element without using its index.
    • 4.4.A.4 Assigning a new value to the enhanced for loop variable does not change the value stored in the array.
    • 4.4.A.5 When an array stores object references, the attributes can be modified by calling methods on the enhanced for loop variable. This does not change the object references stored in the array.
    • 4.4.A.6 Code written using an enhanced for loop to traverse elements in an array can be rewritten using an indexed for loop or a while loop.

    来源:美国大学理事会 AP 课程与考试说明

    用一个 for 循环(给出索引)或一个增强 for / for-each(enhanced for / for-each)循环(给出每个值,只读)遍历(traverse)一个数组:

    for (int i = 0; i < a.length; i++) { a[i] *= 2; }   // can modify
    for (int v : a) { System.out.println(v); }          // read each value
    
    词汇表 训练
    英文 中文 拼音
    Traverse 遍历 biàn lì
    4.5

    实现数组算法

    大纲
    Learning ObjectiveEssential Knowledge

    4.5.A
    Develop code for standard and original algorithms for a particular context or specification that involves arrays and determine the result of these algorithms.

    • 4.5.A.1 There are standard algorithms that utilize array traversals to:
      • determine a minimum or maximum value
      • compute a sum or average
      • determine if at least one element has a particular property
      • determine if all elements have a particular property
      • determine the number of elements having a particular property
      • access all consecutive pairs of elements
      • determine the presence or absence of duplicate elements
      • shift or rotate elements left or right
      • reverse the order of the elements

    来源:美国大学理事会 AP 课程与考试说明

    掌握这些模式:计算一个平均、找最大/最小计数满足一个条件的项、检查一个重复,和反转移位元素。每一个都是一个带连续结果的遍历:

    int sum = 0;
    for (int v : a) sum += v;
    double avg = (double) sum / a.length;
    
    4.6

    使用文本文件

    大纲
    Learning ObjectiveEssential Knowledge

    4.6.A
    Develop code to read data from a text file.

    • 4.6.A.1 A file is storage for data that persists when the program is not running. The data in a file can be retrieved during program execution.
    • 4.6.A.2 A file can be connected to the program using the File and Scanner classes.
    • 4.6.A.3 A file can be opened by creating a File object, using the name of the file as the argument of the constructor.
      • File(String str) is the File constructor that accepts a String file name to open for reading, where str is the pathname for the file.
    • 4.6.A.4 When using the File class, it is required to indicate what to do if the file with the provided name cannot be opened. One way to accomplish this is to add throws IOException to the header of the method that uses the file. If the file name is invalid, the program will terminate.
    • 4.6.A.5 The File and IOException classes are part of the java.io package. An import statement must be used to make these classes available for use in the program.
    • 4.6.A.6 The following Scanner methods and constructor—including what they do and when they are used—are part of the Java Quick Reference:
      • Scanner(File f) is the Scanner constructor that accepts a File for reading.
      • int nextInt() returns the next int read from the file or input source if available. If the next int does not exist or is out of range, it will result in an InputMismatchException.
      • double nextDouble() returns the next double read from the file or input source. If the next double does not exist, it will result in an InputMismatchException.
      • boolean nextBoolean() returns the next boolean read from the file or input source. If the next boolean does not exist, it will result in an InputMismatchException.
      • String nextLine() returns the next line of text as a String read from the file or input source; can return the empty string if called immediately after another Scanner method that is reading from the file or input source.
      • String next() returns the next String read from the file or input source.
      • boolean hasNext() returns true if there is a next item to read in the file or input source; returns false otherwise.
      • void close() closes this scanner.
      • Exclusion statement: Accepting input from the keyboard is outside the scope of the AP Computer Science A course and exam.
    • 4.6.A.7 Using nextLine and the other Scanner methods together on the same input source sometimes requires code to adjust for the methods' different ways of handling whitespace.
      • Exclusion statement: Writing or analyzing code that uses both nextLine and other Scanner methods on the same input source is outside the scope of the AP Computer Science A course and exam.
    • 4.6.A.8 The following additional String method—including what it does and when it is used—is part of the Java Quick Reference:
      • String[] split(String del) returns a String array where each element is a substring of this String, which has been split around matches of the given expression del.
      • Exclusion statement: The parameter del uses a format called a regular expression. Writing or analyzing code that uses any of the special properties of regular expressions (e.g., \\*, \\.) is outside the scope of the AP Computer Science A course and exam.
    • 4.6.A.9 A while loop can be used to detect if the file still contains elements to read by using the hasNext method as the condition of the loop.
    • 4.6.A.10 A file should be closed when the program is finished using it. The close method from Scanner is called to close the file.

    来源:美国大学理事会 AP 课程与考试说明

    FileIOExceptionjava.io 里,所以一个读文件的程序需要 import java.io.*;。打开一个文件可能失败(它也许不存在),Java 强制你处理这一点——最简单的方式是在方法头上加 throws IOException。然后一个 Scanner 逐行读文件,用 hasNext... 在读之前测试:

    import java.io.*;
    ...
    public static void readFile() throws IOException {
        Scanner f = new Scanner(new File("data.txt"));
        while (f.hasNextLine()) {
            String line = f.nextLine();
        }
    }
    

    nextInt()nextDouble()nextBoolean() 读有类型的记号时,如果下一个记号是错误的类型,会抛出一个 InputMismatchException——例如当文件里下一个东西是单词 cat 时调用 nextInt()

    4.7

    包装类

    大纲
    Learning ObjectiveEssential Knowledge

    4.7.A
    Develop code to use Integer and Double objects from their primitive counterparts and determine the result of using these objects.

    • 4.7.A.1 The Integer class and Double class are part of the java.lang package. An Integer object is immutable, meaning once an Integer object is created, its attributes cannot be changed. A Double object is immutable, meaning once a Double object is created, its attributes cannot be changed.
    • 4.7.A.2 Autoboxing is the automatic conversion that the Java compiler makes between primitive types and their corresponding object wrapper classes. This includes converting an int to an Integer and a double to a Double. The Java compiler applies autoboxing when a primitive value is:
      • passed as a parameter to a method that expects an object of the corresponding wrapper class
      • assigned to a variable of the corresponding wrapper class
    • 4.7.A.3 Unboxing is the automatic conversion that the Java compiler makes from the wrapper class to the primitive type. This includes converting an Integer to an int and a Double to a double. The Java compiler applies unboxing when a wrapper class object is:
      • passed as a parameter to a method that expects a value of the corresponding primitive type
      • assigned to a variable of the corresponding primitive type
    • 4.7.A.4 The following class Integer method—including what it does and when it is used—is part of the Java Quick Reference:
      • static int parseInt(String s) returns the String argument as an int.
    • 4.7.A.5 The following class Double method—including what it does and when it is used—is part of the Java Quick Reference:
      • static double parseDouble(String s) returns the String argument as a double.

    来源:美国大学理事会 AP 课程与考试说明

    一个 ArrayList 存储对象,不是基本类型,所以一个基本类型被包装在一个对象里:Integer 包装 int,Double 包装 double。Java 用自动装箱(autoboxing)(intInteger)和拆箱(unboxing)(再回去)自动做这个,所以你能写 list.add(5)int x = list.get(0)

    词汇表 训练
    英文 中文 拼音
    autoboxing 自动装箱 zì dòng zhuāng xiāng
    4.8

    ArrayList 方法

    大纲
    Learning ObjectiveEssential Knowledge

    4.8.A
    Develop code for collections of related objects using ArrayList objects and determine the result of calling methods on these objects.

    • 4.8.A.1 An ArrayList object is mutable in size and contains object references.
    • 4.8.A.2 The ArrayList constructor ArrayList() constructs an empty list.
    • 4.8.A.3 Java allows the generic type ArrayList<E>, where the type parameter E specifies the type of the elements. When ArrayList<E> is specified, the types of the reference parameters and return type when using the ArrayList methods are type E. ArrayList<E> is preferred over ArrayList. For example, ArrayList<String> names = new ArrayList<String>(); allows the compiler to find errors that would otherwise be found at run-time.
    • 4.8.A.4 The ArrayList class is part of the java.util package. An import statement must be used to make this class available for use in the program.
    • 4.8.A.5 The following ArrayList methods—including what they do and when they are used—are part of the Java Quick Reference:
      • int size() returns the number of elements in the list.
      • boolean add(E obj) appends obj to end of list; returns true.
      • void add(int index, E obj) inserts obj at position index (0 <= index <= size), moving elements at position index and higher to the right (adds 1 to their indices) and adds 1 to size.
      • E get(int index) returns the element at position index in the list.
      • E set(int index, E obj) replaces the element at position index with obj; returns the element formerly at position index.
      • E remove(int index) removes element from position index, moving elements at position index + 1 and higher to the left (subtracts 1 from their indices) and subtracts 1 from size; returns the element formerly at position index.
    • 4.8.A.6 The indices for an ArrayList start at 0 and end at the number of elements - 1.

    来源:美国大学理事会 AP 课程与考试说明

    ArrayList 的底层实现

    一个 ArrayList(动态数组)在你添加或移除项时增长和收缩。用 <> 里的元素类型声明它:

    ArrayList<String> names = new ArrayList<String>();
    names.add("Amy");           // append
    names.add(0, "Bob");        // insert at index
    names.get(0);               // read
    names.set(1, "Cara");       // replace
    names.remove(0);            // delete, shifts the rest left
    names.size();               // count (a method, unlike array.length)
    
    词汇表 训练
    英文 中文 拼音
    ArrayList 动态数组 dòng tài shù zǔ
    4.9

    ArrayList 遍历

    大纲
    Learning ObjectiveEssential Knowledge

    4.9.A
    Develop code used to traverse the elements of an ArrayList and determine the results of these traversals.

    • 4.9.A.1 Traversing an ArrayList is when iteration or recursive statements are used to access all or an ordered sequence of the elements in an ArrayList.
    • 4.9.A.2 Deleting elements during a traversal of an ArrayList requires the use of special techniques to avoid skipping elements.
    • 4.9.A.3 Attempting to access an index value outside of its range will result in an IndexOutOfBoundsException.
    • 4.9.A.4 Changing the size of an ArrayList while traversing it using an enhanced for loop can result in a ConcurrentModificationException. Therefore, when using an enhanced for loop to traverse an ArrayList, you should not add or remove elements.

    来源:美国大学理事会 AP 课程与考试说明

    用一个索引循环或一个 for-each 循环遍历,就像数组(用 size()get(i)):

    for (int i = 0; i < list.size(); i++) { ... list.get(i) ... }
    for (String s : list) { ... }
    

    考试技能: 当在一个索引循环里移除项时,要么向后循环,要么在一次移除之后递增 i ——否则移除会把元素向左移动而你跳过一个。而且绝不要在用一个 for-each 循环遍历一个 ArrayList 时添加或移除元素:在循环中途改变它的大小会抛出一个 ConcurrentModificationException,所以每当你必须移除时用一个索引循环(向后,如上)。

    4.10

    实现 ArrayList 算法

    大纲
    Learning ObjectiveEssential Knowledge

    4.10.A
    Develop code for standard and original algorithms for a particular context or specification that involve ArrayList objects and determine the result of these algorithms.

    • 4.10.A.1 There are standard ArrayList algorithms that utilize traversals to:
      • determine a minimum or maximum value
      • compute a sum or average
      • determine if at least one element has a particular property
      • determine if all elements have a particular property
      • determine the number of elements having a particular property
      • access all consecutive pairs of elements
      • determine the presence or absence of duplicate elements
      • shift or rotate elements left or right
      • reverse the order of the elements
      • insert elements
      • delete elements
    • 4.10.A.2 Some algorithms require multiple String, array, or ArrayList objects to be traversed simultaneously.

    来源:美国大学理事会 AP 课程与考试说明

    与数组相同的算法——最大/最小、计数、求和——加上数组不能轻易做的插入删除。一个常见的任务是移除所有匹配一个条件的元素,小心地处理索引移位。

    4.11

    二维数组的创建与访问

    大纲
    Learning ObjectiveEssential Knowledge

    4.11.A
    Develop code used to represent collections of related data using two-dimensional (2D) array objects.

    • 4.11.A.1 A 2D array is stored as an array of arrays. Therefore, the way 2D arrays are created and indexed is similar to 1D array objects. The size of a 2D array is established at the time of creation and cannot be changed. 2D arrays can store either primitive data or object reference data.
      • Exclusion statement: Nonrectangular 2D array objects are outside the scope of the AP Computer Science A course and exam.
    • 4.11.A.2 When a 2D array is created using the keyword new, all of its elements are initialized to the default values for the element data type. The default value for int is 0, for double is 0.0, for boolean is false, and for a reference type is null.
    • 4.11.A.3 The initializer list used to create and initialize a 2D array consists of initializer lists that represent 1D arrays; for example, int[][] arr2D = { {1, 2, 3}, {4, 5, 6} };.
    • 4.11.A.4 The square brackets [row][col] are used to access and modify an element in a 2D array. For the purposes of the exam, when accessing the element at arr[first][second], the first index is used for rows, the second index is used for columns.
    • 4.11.A.5 A single array that is a row of a 2D array can be accessed using the 2D array name and a single set of square brackets containing the row index.
    • 4.11.A.6 The number of rows contained in a 2D array can be accessed through the length attribute. The valid row index values for a 2D array are 0 through one less than the number of rows or the length of the array, inclusive. The number of columns contained in a 2D array can be accessed through the length attribute of one of the rows. The valid column index values for a 2D array are 0 through one less than the number of columns or the length of any given row of the array, inclusive. For example, given a 2D array named values, the number of rows is values.length and the number of columns is values[0].length. Using an index value outside of these ranges will result in an ArrayIndexOutOfBoundsException.

    来源:美国大学理事会 AP 课程与考试说明

    一个 2D 数组(2D array)是一个网格(行和列)——一个数组的数组:

    一个二维数组(一张表),带行和列索引
    一个二维数组(一张表),带行和列索引
    int[][] grid = new int[3][4];   // 3 rows, 4 columns
    grid[r][c] = 7;                 // row r, column c
    int rows = grid.length;         // 3
    int cols = grid[0].length;      // 4
    
    探索

    Index a 2D array by row and column

    A 2D array is a grid addressed by [row][col]. Move the indices and watch which cell they select — row first, then column, both counting from 0.

    词汇表 训练
    英文 中文 拼音
    2D array 二维数组 èr wéi shù zǔ
    4.12

    二维数组遍历

    大纲
    Learning ObjectiveEssential Knowledge

    4.12.A
    Develop code used to traverse the elements in a 2D array and determine the result of these traversals.

    • 4.12.A.1 Nested iteration statements are used to traverse and access all or an ordered sequence of elements in a 2D array. Since 2D arrays are stored as arrays of arrays, the way 2D arrays are traversed using for loops and enhanced for loops is similar to 1D array objects. Nested iteration statements can be written to traverse the 2D array in row-major order, column-major order, or a uniquely defined order. Row-major order refers to an ordering of 2D array elements where traversal occurs across each row, whereas column-major order traversal occurs down each column.
    • 4.12.A.2 The outer loop of a nested enhanced for loop used to traverse a 2D array traverses the rows. Therefore, the enhanced for loop variable must be the type of each row, which is a 1D array. The inner loop traverses a single row. Therefore, the inner enhanced for loop variable must be the same type as the elements stored in the 1D array. Assigning a new value to the enhanced for loop variable does not change the value stored in the array.

    来源:美国大学理事会 AP 课程与考试说明

    遍历二维数组

    嵌套循环(nested loops)访问每个单元格——外层遍历行、内层遍历列(行主序(row-major order)):

    for (int r = 0; r < grid.length; r++)
        for (int c = 0; c < grid[0].length; c++)
            System.out.print(grid[r][c]);
    
    词汇表 训练
    英文 中文 拼音
    row-major order 行主序 xíng zhǔ xù
    4.13

    实现二维数组算法

    大纲
    Learning ObjectiveEssential Knowledge

    4.13.A
    Develop code for standard and original algorithms for a particular context or specification that involves 2D arrays and determine the result of these algorithms.

    • 4.13.A.1 There are standard algorithms that utilize 2D array traversals to:
      • determine a minimum or maximum value of all the elements or for a designated row, column, or other subsection
      • compute a sum or average of all the elements or for a designated row, column, or other subsection
      • determine if at least one element has a particular property in the entire 2D array or for a designated row, column, or other subsection
      • determine if all elements of the 2D array or a designated row, column, or other subsection have a particular property
      • determine the number of elements in the 2D array or in a designated row, column, or other subsection having a particular property
      • access all consecutive pairs of elements
      • determine the presence or absence of duplicate elements in the 2D array or in a designated row, column, or other subsection
      • shift or rotate elements in a row left or right or in a column up or down
      • reverse the order of the elements in a row or column

    来源:美国大学理事会 AP 课程与考试说明

    典型的网格任务:求一行或一列的和、找网格里的最大值、计数匹配的单元格,或求一条对角线的和(r == c 的地方)。每一个都是一个带连续结果的嵌套遍历。

    4.14

    查找算法

    大纲
    Learning ObjectiveEssential Knowledge

    4.14.A
    Develop code used for linear search algorithms to search for specific information in a collection and determine the results of executing a search.

    • 4.14.A.1 Linear search algorithms are standard algorithms that check each element in order until the desired value is found or all elements in the array or ArrayList have been checked. Linear search algorithms can begin the search process from either end of the array or ArrayList.
    • 4.14.A.2 When applying linear search algorithms to 2D arrays, each row must be accessed then linear search applied to each row of the 2D array.

    来源:美国大学理事会 AP 课程与考试说明

    二分查找
    • 线性搜索(linear search)依次检查每个元素——在任何列表上起作用,取最多 $n$ 步。
    • 二分搜索(binary search)只在一个排序的列表上起作用:检查中间、然后丢弃不能包含目标的那一半,重复。它取约 $\log_2 n$ 步——在大数据上快得多。
    二分搜索在每一步把范围减半
    二分搜索在每一步把范围减半
    线性搜索依次检查每个元素直到目标被找到
    线性搜索依次检查每个元素直到目标被找到
    int lo = 0, hi = a.length - 1;
    while (lo <= hi) {
        int mid = (lo + hi) / 2;
        if (a[mid] == target) return mid;
        else if (a[mid] < target) lo = mid + 1;
        else hi = mid - 1;
    }
    

    考试技能: 二分搜索需要排序的数据;知道它做多少次比较以及 lohimid 如何更新。

    Worked example. 在排序的数组 {3, 9, 14, 23, 31, 42, 55}(索引 06)里搜索 target = 40。开始 lo=0, hi=6:

    • mid = (0+6)/2 = 3,a[3]=23 < 40,所以 lo = 4;
    • mid = (4+6)/2 = 5,a[5]=42 > 40,所以 hi = 4;
    • mid = (4+4)/2 = 4,a[4]=31 < 40,所以 lo = 5;
    • 现在 lo (5) > hi (4),所以循环结束——40 不存在

    每一步把范围减半,所以即使这次未命中也只取三次比较。

    探索

    Compare linear and binary search

    Linear search checks every element in turn; binary search halves a sorted list each step. Watch binary search reach the target in far fewer comparisons.

    词汇表 训练
    英文 中文 拼音
    Linear search 线性搜索 xiàn xìng sōu suǒ
    Binary search 二分搜索 èr fēn sōu suǒ
    4.15

    排序算法

    大纲
    Learning ObjectiveEssential Knowledge

    4.15.A
    Determine the result of executing each step of sorting algorithms to sort the elements of a collection.

    • 4.15.A.1 Selection sort and insertion sort are iterative sorting algorithms that can be used to sort elements in an array or ArrayList.
    • 4.15.A.2 Selection sort repeatedly selects the smallest (or largest) element from the unsorted portion of the list and swaps it into its correct (and final) position in the sorted portion of the list.
    • 4.15.A.3 Insertion sort inserts an element from the unsorted portion of a list into its correct (but not necessarily final) position in the sorted portion of the list by shifting elements of the sorted portion to make room for the new element.

    来源:美国大学理事会 AP 课程与考试说明

    插入排序
    冒泡排序
    • 选择排序(selection sort)反复找到最小的剩余元素并把它交换到位。
    • 插入排序(insertion sort)增长一个排序的前部,把每个新元素插入到它所属的地方。
    一个插入排序,一趟一趟地把每个键移到位
    一个插入排序,一趟一趟地把每个键移到位

    两者都简单,平均取约 $n^2$ 步——对小数组还行。能够跟踪每一趟之后的数组。

    探索

    Watch a sorting algorithm order a list

    A sort rearranges elements into order. Step through selection/insertion sort to see the sorted region grow one element at a time.

    词汇表 训练
    英文 中文 拼音
    Selection sort 选择排序 xuǎn zé pái xù
    Insertion sort 插入排序 chā rù pái xù
    4.16

    递归

    大纲
    Learning ObjectiveEssential Knowledge

    4.16.A
    Determine the result of calling recursive methods.

    • 4.16.A.1 A recursive method is a method that calls itself. Recursive methods contain at least one base case, which halts the recursion, and at least one recursive call. Recursion is another form of repetition.
    • 4.16.A.2 Each recursive call has its own set of local variables, including the parameters. Parameter values capture the progress of a recursive process, much like loop control variable values capture the progress of a loop.
    • 4.16.A.3 Any recursive solution can be replicated through the use of an iterative approach and vice versa.
      • Exclusion statement: Writing recursive code is outside the scope of the AP Computer Science A course and exam.

    来源:美国大学理事会 AP 课程与考试说明

    递归与调用栈

    递归(recursion)是一个在一个更小的输入上调用它自己的方法。它需要一个停止调用的基本情况(base case),和一个朝基本情况移动的递归情况(recursive case):

    public static int factorial(int n) {
        if (n <= 1) return 1;          // base case
        return n * factorial(n - 1);   // recursive case
    }
    

    没有一个可达的基本情况,递归从不停止(一个栈溢出)。

    递归和迭代是可以互换的。任何递归解法都能用一个循环(迭代方式)改写,而任何循环也都能用递归改写 —— 它们解决的是同一类问题。上面的 factorial 与一个迭代版本效果完全相同:

    public static int factorial(int n) {
        int result = 1;
        for (int i = 2; i <= n; i++) result *= i;   // same answer, no self-call
        return result;
    }
    

    所以这个选择关乎清晰度,而非能力:对于具有自相似结构的问题(树、归并排序),递归读起来很自然;而迭代则避免了每一步都压入一个调用帧的内存开销。考试可能会要求你把其中一种转换成另一种。

    探索

    Unfold a recursive call

    A recursive method calls itself on a smaller input until it hits a base case, then the results fold back up. Step through to watch the calls stack and unwind.

    词汇表 训练
    英文 中文 拼音
    Recursion 递归 dì guī
    base case 基本情况 jī běn qíng kuàng
    4.17

    递归查找与排序

    大纲
    Learning ObjectiveEssential Knowledge

    4.17.A
    Determine the result of executing recursive algorithms that use strings or collections.

    • 4.17.A.1 Recursion can be used to traverse String objects, arrays, and ArrayList objects.

    4.17.B
    Determine the result of each iteration of a binary search algorithm used to search for information in a collection.

    • 4.17.B.1 Data must be in sorted order to use the binary search algorithm. Binary search starts at the middle of a sorted array or ArrayList and eliminates half of the array or ArrayList in each recursive call until the desired value is found or all elements have been eliminated.
    • 4.17.B.2 Binary search is typically more efficient than linear search.
      • Exclusion statement: Search algorithms other than linear and binary search are outside the scope of the AP Computer Science A course and exam.
    • 4.17.B.3 The binary search algorithm can be written either iteratively or recursively.

    4.17.C
    Determine the result of each iteration of the merge sort algorithm when used to sort a collection.

    • 4.17.C.1 Merge sort is a recursive sorting algorithm that can be used to sort elements in an array or ArrayList.
      • Exclusion statement: Sorting algorithms other than selection, insertion, and merge sort are outside the scope of the AP Computer Science A course and exam.
    • 4.17.C.2 Merge sort repeatedly divides an array into smaller subarrays until each subarray is one element and then recursively merges the sorted subarrays back together in sorted order to form the final sorted array.

    来源:美国大学理事会 AP 课程与考试说明

    归并排序

    递归驱动高效的算法。二分搜索能被递归地写(搜索正确的那一半)。归并排序(merge sort)把数组分成一半、递归地排序每一半,然后归并两个排序的一半——取约 $n\log_2 n$ 步,在大数据上比选择或插入排序快得多。

    归并排序把数组分裂到单个元素,然后把排序的一半向上归并
    归并排序把数组分裂到单个元素,然后把排序的一半向上归并

    Worked example. 跟踪 factorial(4)。每个调用推迟给一个更小的:factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * 2 * factorial(1)factorial(1) 命中基本情况并返回 1,所以调用向内展开:2 * 1 = 2,然后 3 * 2 = 6,然后 4 * 6 = 24。把每个调用写在它返回值的上方是跟踪递归的可靠方式。

    考试技能: 通过写出每个调用和它的返回值来跟踪一个递归方法,并知道归并排序的效率($n\log n$)击败 $n^2$ 的简单排序。

    词汇表 训练
    英文 中文 拼音
    Merge sort 归并排序 guī bìng pái xù
    4.17

    考试技巧

    • 权衡收集数据的好处和害处——这个单元通过简短的书面论证考查,不是代码。
    • 保护个人身份信息(PII)(personally identifiable information)并在上下文里解释隐私和安全风险。
    • 命名真实的害处:数据泄露、监视,和来自不具代表性数据的算法偏见
    • 当你重用代码或数据时尊重知识产权和许可。
    • 给出一个具体的、有理由的答案——一个模糊的"它可能是坏的"不赢得分数。

登录或创建账号

IGCSE, A-Level & AP