Initialization
初始化
* All class-level (member) variables are initialized before they can
be used.
All local variables are not initialized until it is done explicitly.
* 所有的主成员在他们使用之前被初始化
所有的局部变量必须通过显式的赋值来初始化
* An array object (as distinct from reference) is always initialized
(with zeroes or s)
* 数组对象总是能够初始化(零或者)
* Member initialization with the declaration has exception problems:
- cannot call methods that throw a checked exception.
- cannot do error recovery from runtime exceptions.
- If you need to deal with errors you can put the initialization code
along with try/catch statements in either a ctor (for instance fields)
or in a static initialization block for static fields. You can also have
instance (non-static) initialization blocks but ctors are more
recognizable.
* 需要处理异常的成员初始化
- 不能调用会抛出异常的方法
- 不能对基本异常做任何处理
- 如果你需要处理错误,将初始化的代码放到构造器或者静态初始化块的
try/catch块中,当然,你也可以放到非静态的代码块中,但是构造器似乎更为通用。
------------------------------------------------------------------------
Strings
字符串
* The String class
- Because string is an immutable class, its instance methods that
look like they would transform the object they are invoked upon,
do not alter the object and instead return new String objects.
- String has methods concat(String),trim(),replace(char,char)
- String has static valueOf methods for a whole bunch of primitives
and for Object too (equivalent to Object.toString()).
- in substring(int,int), the second arg is exclusive.
- indexOf methods returns -1 for 'not found'
* 类String
- 类String是不可变的,即使他的某些方法看起来会改变字符串的内容,但实际
上他们返回的是一个新的字符串,而不是改变原来的字符串
- 类String的方法:cancat(String),trim(),replace(char,char)
- 类String的静态方法valueOf能处理所有的基本类型和对象(调用对象的
toString()方法)
- 在substring(int,int)方法中,第二个参数是"不包括"的(译者注:第一个参
数是"包括"的,例如substring(1,4)将会返回字符串从第二个字符开始(包括
第二个字符),到第五个字符结束(不包括第五个字符)的子字符串)
- 如果没有找到,indexOf方法将返回-1
* String Pool:
A JVM has a string pool where it keeps at most one object of any
String. String literals always refer to an object in the string
pool. String objects created with the new operator do not refer to
objects in the string pool but can be made to using String's intern()
method. Two String references to 'equal' strings in the string pool
will be '=='.
* 字符串池
虚拟机有一个字符串池,保存着几乎所有的字符串对象。字符串表达式总是指向
字符串池中的一个对象。使用new操作创建的字符串对象不指向字符串池中的对象
但是可以使用intern方法使其指向字符串池中的对象(译者注:如果池中已经有
相同的字符串--使用equals方法确定,则直接返回池中的字符串,否则先将字符串
添加到池中,再返回)。池中两个相等的字符串如果使用'=='来比较将返回真
* StringBuffer doesn't override equals.
* 类StringBuffer没有覆盖equals方法
------------------------------------------------------------------------
Arrays
数组
* Arrays are objects .. the following create a reference for an int array.
int[] ii;
int ii[];
* 数组是一个对象 .. 下面的代码创建一个整型数组的引用:
int[] ii;
int ii[];
* You can create an array object with new or an explicit initializer:
ii = new int[3];
ii = new int[] { 1,2,3 };
int[] ii = { 1,2,3 ); // only when you declare the reference.
* 你可以通过new操作或者显式的初始化创建一个数组对象:
ii = new int[3];
ii = new int[] { 1,2,3 };
int[] ii = { 1,2,3 }; // 只有声明的时候
* CAREFUL: You can't create an array object with:
int iA[3];
* 小心:你不能象下面这样创建一个数组对象:
int iA[3];
* If you don't provides values, the elements of obj arrays are
always initialized to and those of primitive arrays are
always initialized to 0.
* 如果你不提供初始值,对象数组的元素总是初始化成,基本类型数组的元素
总是初始化成零
------------------------------------------------------------------------
Primitive Types
基本类型
* Primitive types:
- short and char are both 2 bytes.
int and float are both 4 bytes.
long and double are both 8 bytes.
- char is the only unsigned primitive type.
* 基本类型:
- short和char的长度是两个字节。
int和float的长度都是四个字节。
long和double的长度都是八个字节。
- char是唯一的无符号基本类型
* Literals:
- You can have boolean, char, int, long, float, double and String
literals.
You cannot have byte or short literals.
- char literals: 'd' 'u0c20' (the 0c20 must be a 4-digit hex number).
- int literals: 0x3c0 is hex, 010 is octal(for 8).
- You can initialize byte, short and char variables with int literals
(or const int expressions) provided the int is in the appropriate range.
* 表达式
- 只有boolean,char,int,long,float,double和字符串的表达式;没有byte
和short的表达式
- 字符(char)表达式:'d'、'u0c20'(0c20必须是四位的十六进制数字)
- 整型(int)表达式:0x3c0是十六进制形式,010是八进制形式
- 可是使用合法范围内的整型表达式对byte、short和char变量初始化
* CAREFUL: can't assign a double literal to a float .. float fff = 26.55;
* 小心:不能将一个double表达式赋给一个float变量 .. float fff = 26.55;
* The only bit operators allowed for booleans are &^| (cant do ~ or
shift ops)
* 位运算只有&^|(不能使用~或者移位操作)
* Primitive wrapper classes
- are immutable.
- override equals.
- the static valueOf(String) methods in primitive wrapper classes return
wrapper objects rather than a primitives.
* 基本类型的包装类
- 不可变的
- 覆盖equals方法
- 静态方法valueOf(String)返回的是包装类而不是基本类型
------------------------------------------------------------------------
Conversions and Promotions
类型转换
* boolean->anything but boolean or string is not allowed.
* All other primitive conversions are allowed with an explicit cast.
* char/byte/short/int/long to float/double is a widening conversion even
if some precision is lost (the overall magnitude is always preserved).
* Narrowing conversions require an explicit cast.
- integral narrowing conversions simply discard high-order bits.
- anything to char is a narrowing conversion (inc byte) because its
signed to unsigned and negative numbers get messed up
* 所有的基本类型之间可以通过显式的类型转换而转变成其它类型
* char/byte/short/int/long到float/double的转换是宽转换,即使有可能丢掉部
分信息
* 窄转换需要显式的转换
- 整型的窄转换只简单的去掉高位比特
- 所有到char的转换都是窄转换(包括byte)因为转换是从有符号数到无符号数
的转换,负数将会得到一个混乱的结果
* Widening primitive and reference conversions are allowed for assignment
and in matching the arguments to a method (or ctor) call.
* 对象和基本类型的宽转换允许在赋值和匹配的方法调用中(非显式的)使用
* For assignment (but not method invocation), representable constant
int expressions can be converted to byte, char or shorts (eg. char c =
65).
* 赋值时,合法的整型表达式能被自动转换成byte、char或者short(例如:
char c = 65)
* Unary numeric promotions: byte/short/char to int
* 一元运算时,byte/short/char将自动转换成int
* Binary numeric promotions:
- both arguments are made (in order of preference)
double/float/long/int.
- include (in)equality operators.
* 二进制数据类型转换:
- 所有的参数自动转换成(按循序的)double/float/long/int
- 包括比较运算
* char/byte/short are promoted to int for nearly every operator ... be
careful not to assign the uncast int return value to a narrower type,
bytesum = byte1 + byte2; // won't compile without a cast.
bytesum += byte2; // is ok.
- applies to bitshift operators (as a unary promotion on each arg).
- applies to unary + and - (eg. byte b = +anotherByte; needs a cast).
- there are no promotions for ++, --, += etc.
byte b=10;
char c = b++; //explicit cast needed to convert byte to char
char c = b++ +10; //explicit cast needed to convert int to char
char c = b++ +10L; //explicit cast needed to convert long to char
* char/byte/short几乎在所的运算中都被转换成int … 要当心不要将int类型的
返回值在没有显式转换之前赋给一个更小的类型:
bytesum = byte1 + byte2; //没有显式的转换不能通过编译
bytesum += byte2; // 没有问题
- 本规则适合于位运算(以及每个一元运算的参数)
- 本规则不适用于++,--,+=等操作
byte b = 10;
char c = b++; //需要显式的将byte转换成char
char c = b++ + 10; //需要显式的将int转换成char
char c = b++ + 10L; //需要显式的将long转换成char
* A switch argument can be any type that can implicit-cast to an int
(byte/char/short/int but not boolean or long).
- The argument and cases can also be compile-time constant
expressions.
* switch的参数可以是任何可以自动转换成int型的基本类型(
byte/char/short/int是合法的参数,但是boolean和long型是不合法的)
- switch的参数和case的参数可以是常量表达式
* Explicit Casting:
- Impossible casts are detected at compile time.
Other bad casts cause runtime exceptions rather than messes.
* 显式的转换
- 不可能的转载编译期间就能检测到。其他错误的转换将抛出异常以防止数据的
混乱
* Array casts:
- The only implicit conversion for arrays is: Base[] base = new Der[5];
- a runtime exception is thrown if you try to add anything but Derived
- There are no implicit casts for arrays of primitives.
- You can make an explicit array cast:
String[] strs = (String[]) ObjectArray;
* 数组转换:
- 对象数组唯一的自动转换的情况是:Base[] base = new Der[5];
- 如果你尝试添加Derived以外的对象,将会得到一个运行期异常
- 基本类型数组没有自动转换的情况
- 可以使用显式的数组类型转换:
String[] strs = (String[]) ObjectArray;
------------------------------------------------------------------------
Bitshift operators
位移操作
- The left-hand argument to a bitshift operator can be an int, long
or any type that can be implicit cast to int (byte,char,short).
- 左侧的参数必须为int,long,或者任何可以自动转换成int的类型(byte,
char,short)
- char, byte, or short arguments will be promoted to int before the shift
takes place, and the result will be an int (so has to be cast to get back
to the original type).
- char,byte或者short型的参数在位移操作之前被自动转换成int型,结果类型为
int(所以你需要显式的将返回类型转换成原来的类型)
- You can't shift futher than the number of bits in the left-hand argument
(int or long). Only the five (six) low-order bits of the right-hand
argument will be used to shift an int (long).
- 你不能移动比左侧参数(int或者long)的长度长的位数。右边参数只有低五(
六)位被用来移动左侧的int(long)类型数据
- Each left-shift (signed-right-shift) for positive numbers is equivalent
to multiplication (division) by 2. The division is rounded down.
- 左移(有符号数右移)操作相当于乘(除)二运算。(…)
------------------------------------------------------------------------
------------------------------------------------------------------------
Object-oriented concepts
面向对象的概念
* The signature of a method is its name, argument type and argument order.
- an overload is legal provided the two methods have different signatures.
- an override must have the same signature and return type, throw no new
checked exceptions and be at least as accessible as the method it is
overriding.
* 一个方法通过它的名字,参数类型以及顺序来标识
- 有不同标识的方法重载是合法的
- 方法覆盖必须有相同的标识和返回值,不能抛出新的普通异常,不能比他要覆
盖的方法拥有更少的权限
* Fields do not act polymorphically:
- whenever you access a field from outside the class, the declared type of
the reference is used rather than the type of the object it refers to.
- regardless of the type of the reference, a method will always access its
own fields rather than those of a derived class.
* 变量成员没有多态性
- 当你从类外面引用变量成员时,你总是得到定义的类型,而非实际指向的类型
- 不管变量成员的类型是什么,方法总是使用类自己的变量成员,而不是其他的
继承过来的变量成员
* Private method calls are statically bound ... a method will call
the private method in the class where it is defined .. even if the
calling method is inherited by a derived class and the derived
class defines a method with the same signature as the private method.
* 私有方法的调用是静态绑定的 … 方法可以调用他所在类之内的私有方法 .. 即
使调用的方法的夫类中有与此私有方法标识相同的方法
* Calls to public and protected methods in the same class are dynamically
bound ... even for constructors (and from private methods). This is
different to C++.
* 对公共的和保护的方法的调用是动态绑定的 … 同样构造函数(不同于私有方法?)
也是动态绑定的。这是与C++不同的地方
* Re-using a static method's name in a derived class:
- A static method cannot be overriden by a non-static method
- A static method can be overriden by a static method but does not
dynamically bind (therefore static methods can't be abstract)
- You can overload a static method with a non-static method.
* note also that a static method can be inherited.
* note that a static var can be 'overriden' by a non-static var.
* 重用夫类中的静态方法的名字:
- 静态方法不能被非静态的方法覆盖
- 静态方法可以被静态方法覆盖,但是不能动态绑定(所以静态方不能是抽象的)
- 可以使用非静态的方法重载静态的方法
* 注意静态方法是可以继承的
* 注意静态的变量可以被非静态的变量"覆盖"
* It's legal to assign any reference type including an Interface reference
to an Object reference .. which makes sense because the interface ref
must point to an Object (or ).
* 讲任何类型的引用包括接口的引用付给一个Object的引用是合法的 .. 应为一个
接口的引用总是指向一个Object(或者)
------------------------------------------------------------------------
Nested classes
-> from the Java Language Specification
-> from Sun's Java Tutorial
嵌套类
-> 来自Java语言规范
-> 来自Sun的Java教程
*** A nested class is a class that is defined inside another class.
*** 嵌套类是定义在另外一个类的内部的类
* There are two distinct types of nested classes:
- static nested classes (or top-level nested classes)
- inner classes (which are always associated with an instance of
an enclosing class).
* 有两种截然不同的嵌套类
- 静态的嵌套类(或者说顶层的嵌套类)
- 内部类(总是定义在其他类的实例里面)
* (Nested) inner class types:
- member classes,
- local classes (method or code block),
- anonymous classes.
* (嵌套的)内部类:
- 成员类
- 局部类(方法或者代码块)
- 匿名类
* Top-level classes (all classes are either top-level or inner)
- static nested classes,
- package member classes.
* 顶层类(所有的类不是顶层类就是内部类)
- 静态的嵌套类
- 包成员类
* Access to enclosing class:
- all outer-class members (inc. private) are accessible to an inner
class [Usually without scope modifiers, but if they are hidden by
an inner class name, you can use Outer.this.outerVar]
- static nested classes cannot acccess instance variables from enclosing
classes (there is no instance), but can access their static variables
(and classes i would think).
* 内部类的权限
- 外部类所有的成员(比如私有的)都有权限访问内部类 [通常没有任何的权限
修饰,但是如果对内部类是隐藏的,可以通过Outer.this.outerVar来引用]
- 静态内部累不可以引用外部类的实例变量(没有实例),但是可以引用外部类
的静态变量(我想,引用静态的类也是允许的)
* Instantiation:
- For accessible inner classes: Outer.Inner i = new Outer().new Inner();
Even if you are in Outer's scope, you need to have an Outer instance.
- For accessible static nested classes:
Outer.Nested nested = new Outer.Nested();
* 实例化:
- 内部类的引用:Outer.Inner i = new Outer().new Inner();
即使在外部类的范围内,你也需要一个外部类的实例
- 静态内部类的引用:Outer.Nested nested = new Outer.Nested();
* Local inner classes cannot access non-final local variables or method
arguments.
* 局部内部类不能引用非最终(final)的局部变量和方法参数
* Nested classes generally have the same options with regard to
modifiers as do variables declared in the same place.
* 嵌套类可以与同等位置上的变量拥有相同的权限修饰
* Unlike class-level nested classes, local classes are executed in the
method's sequence of execution so you can't create an instance of the
local class before it is declared.
* 与类一级的内部类不同的是,局部类是按次序执行的,所以你不能在定义之前创
建一个类的实例
* The static keyword marks a top-level construct (class, method or
field) and can never be subject to an enclosing instance.
- no inner class can have a static member.
- no method can have a static member.
* 关键字static使一个顶层的构造(类,方法或者成员变量)不属于他的外部类实例
- 内部类不能有静态成员
- 方法不能有静态成员
* Interfaces automatically attach 'public static final' to field and
class members (thus making them top-level nested rather than member
inner classes).
* 接口自动将"public static final"的权限修饰赋予所有的成员变量和方法(这
将保证它们是顶层嵌套的而不是内部成员类)
* A nested class cannot have the same simple name as any of its
enclosing classes (note: there is no similar restriction on method
or variable names).
* 嵌套类不能使用与它的任何外部类的名字相同的名字来命名(注意:方法和变量
并没有这个限制)
------------------------------------------------------------------------
------------------------------------------------------------------------
Threads
线程
* Know where the basic thread methods are:
- wait, notify and notifyAll are Object instance methods.
- start, stop, suspend, resume and interrupt are Thread instance methods.
- sleep and yield are Thread static methods
* 了解基本的线程方法的位置:
- wait,notify和notifyAll是Object的实例方法
- start,stop,suspend,resume和interrupt是Thread的实例方法
- sleep和yield是Thread的静态方法
* Thread states:
- Bruce Eckel lists 4 thread states: new, runnable, blocked, dead.
* 线程的状态
- Bruce Eckel 列出四种线程状态:创建,可运行的,堵塞的,死亡
* Blocking
- There are 5 ways a thread can be blocked - sleep, wait, suspend,
synchronization, io blocking.
- sleep and suspend do not release locks held by the thread.
* 堵塞的
- 有五种方法可以使一个线程堵塞 - sleep,wait,suspend,同步,io堵塞
- sleep和suspend期间线程不释放对象的锁
* Deprecated methods
- stop is unsafe because it releases all locks and may leave objects in
an inconsistent state.
- suspend is deprecated because its failure to release locks makes it
prone to deadlock. Calling wait in a sync block is safer.
* 不推荐使用的方法
- stop方法因为释放所有的锁而导致有可能使线程进入不一致的状态,不安全
- suspend不推荐使用是因为它不能释放锁而导致有可能进入死锁状态。在同步
代码里使用wait会更安全
* The isAlive method returns false for new threads as well as dead threads.
* isAlive方法在线程创建和死亡的状态下都返回false
* Threads inherit their priority from the thread that calls their ctor.
* 线程继承调用他们的构造函数的线程的优先级
------------------------------------------------------------------------
Exceptions
异常
* Non-runtime exceptions are called checked exceptions.
* 非运行期异常叫普通异常
* Even if a method explicitly throws a runtime exception, there is no
obligation for the caller to acknowledge the exception. One consequence
of this is that the restriction on exceptions thrown by an overriding
method only applies to checked exceptions.
* 如果方法抛出运行期异常,调用者没有必要知道。由此推论出,方法覆盖抛出异
常的限制只适用于普通异常
* A try block's finally clause is called unless the JVM is exited (i think).
- a return in try or catch does not prevent finally from being executed.
* try块的fanally字句总是被执行,除非程序推出虚拟机(我想是这样的)
- try或者catch里面的语句不能阻止finally字句的执行
* A try block's finally statement will be executed (unless the thread dies)
before control leaves the try/catch/finally scope. It will be executed
before unhandled exceptions (from try or catch) are passed back up the
calling stack.
* try块的finally字句在退出try/catch/finally之前执行(除非线程已经死亡)。
它将会在将没有捕捉的异常(产生于try或者catch)送回调用堆栈之前执行
* If you return from a try and finally does not return ... 1) the return
value is calculated, 2) finally executes and 3) the method returns with
the value calculated prior to executing finally.
* 如果你从try字句返回并且finally字句不包含返回 … 1) 计算返回值,2) 执行
finally字句, 3) 方法返回执行finally之前计算的结果
* If you have a return in both try and finally, the finally's value
is always returned.
* 如果你同时在try和finally中返回,则总是返回finally中的返回值
* If try/catch excludes continuation following finally, it is a compile
error to have any statements there.
* 在try/catch和finally之间放置任何语句将会导致编译错误
* Primitive floating point operations do not throw exceptions. They use
NaN and infinity instead.
* 基本的浮点运算不会抛出异常,它们使用NaN和infinity来表示异常的结果
* A constructor can throw any exception.
* 构造函数可以抛出任何异常
------------------------------------------------------------------------
Streams
流
* System.in is an InputStream and out and err are PrintStreams.
* System.in是一个InputStream,out和err是PrintStream
* Beware of instances of the abstract OutputStream and InputStream.
* 慎防实例化抽象的OutputStream和InputStream
* Some OutputStreams:
OutputStream
- write(int) writes the eight low-order bits to the underlying stream
- write(byte[]) write(byte[],int off,int len)
- flush()
- close()
BufferedOutputStream
- has two ctors: (OutputStream) (OutpuStream, int size)
DataOutputStream
- writes primitives and strings to a byte-based stream.
ObjectOutputStream
- writes primitives, strings and serializable objects (inc arrays).
- is not a FilterOutputStream (seems strange).
PrintStream
- two ctors: (OutputStream) (OutputStream, boolean autoflush)
- never throws IOExceptions (sets internal flag instead)
- print and println for primitives and strings.
- print(Object) prints Object.toString().
- System.out and System.err are printstreams.
FileOutputStream
- 4 constructors: (File) (FileDescriptor) (String)
(String, boolean append)
PipedOutputStream
- two ctors: () (PipedInputStream)
- method to connect(PipedInputStream)
ByteArrayOutputStream
- 2 ctors: () (int size)
* 一些OutputStream:
OutputStream
- write(int) 将int的低八位写入底层的流
- write(byte[]) write(byte[],int off,int len)
- flush()
- close()
BufferedOutputStream
- 两个构造函数:(OutputStream) (OutpuStream, int size)
DataOutputStream
- 将基本类型和字符串写入基于字节的流
ObjectOutputStream
- 写入基本类型,字符串和串行化的对象(例如数组)
- is not a FilterOutputStream (seems strange).
PrintStream
- 两个构造函数:(OutputStream) (OutputStream, boolean autoflush)
- 永远不会抛出IOException(取而代之的是设置某些标记位)
- print and println的参数可以是基本类型和字符串
- print(Object)打印Object.toString().
- System.out和System.err是PrintStream
FileOutputStream
- 四个构造函数:(File) (FileDescriptor) (String)(String, boolean append)
PipedOutputStream
- 两个构造函数:() (PipedInputStream)
- 方法connect(PipedInputStream)
ByteArrayOutputStream
- 两个构造函数:() (int size)
* Some Writers
- OutputStreamWriter
- StringWriter, CharArrayWriter - like ByteArrayOutputStream
- FileWriter, BufferedWriter, PrintWriter, FilterWriter
- There is no ObjectWriter, DataWriter.
- PrintWriter can be constructed with an OutputStream or Writer.
* 一些Writer
- OutputStreamWriter
- StringWriter, CharArrayWriter - 与ByteArrayOutputStream相似
- FileWriter, BufferedWriter, PrintWriter, FilterWriter
- 没有ObjectWriter, DataWriter.
- PrintWriter可以使用OutputStream或者Writer来构造
* Some Readers:
- LineNumberReader doesn't attach numbers, it has getLineNumber().
- CharArrayReader is ctd with the char[] that it reads from and
optional int start position and length args.
* 一些Reader:
- LineNumberReader并不会附加行号,可以通过getLineNumber()方法取得行号
- CharArrayReader使用char[]来构造,从char[]中读取数据,参数int start和
length是可选的
* RandomAccessFile
- does not extend File or any type of stream.
- two ctors: ( File or String name, String mode="r","rw" )
- checks for read/write access at construction (unlike File).
- has read/write methods for primitives and strings (and a couple of
others).
- has a (long//mahachanged fm byte to long) file-pointer: seek(long),
long length().
* RandomAccessFile
- 并非继承自File或者任何类型的流
- 连个构造函数:( File or String name, String mode="r","rw" )
- 在初始化时检查文件的读写权限(不同于File)
- 对基本类型和字符串(还有其他的)有专门的读写方法
- 有一个long型的文件指针:seek(long), long length().
* FileDescriptor
- just a handle to a sink/source of bytes.
- only has two methods: sync() and valid()
* FileDescriptor
- 只是作为字节接收器/源的一个句柄
- 只有两个方法:sync() and valid()
* File
- represents an abstract file or dir pathname (file/dir doesnt have
to exist).
- 3 ctors: (File or String parent, String child) (String pathname)
* File
- 对抽象的文件或者目录的描述(文件/目录不一定存在)
- 三个构造函数:(File or String parent, String child) (String pathname)
------------------------------------------------------------------------
Collections
集合
* The Collection interface is extended by Set and List (and SortedSet).
- a set contains no duplicates.
- a list is a sequence and can have duplicates.
* The Map interface does not extend Collection and is extended by
SortedMap.
* Set、List和SortedSet继承自Collection
- Set不包含重复的元素
- List是有序的,可以包含重复的元素
* Map并非Collection的子类,SortedMap继承自Map
* There are abstract classes for each of the main interfaces (Collection,
Set, List and Map) and implementations extend these.
* 主要的接口都有相对应的抽象类,具体的实现从抽象类继承
* Set implementations
- HashSet
- TreeSet (implements SortedSet)
* List implementations
- ArrayList
- LinkedList
* Map implementations
- HashMap
- TreeMap (implements SortedMap)
* 实现Set的类
- HashSet
- TreeSet(实现SortedSet)
* 实现List的类
- ArrayList
- LinkedList
* 实现Map的类
- HashMap
- TreeMap(实现SortedMap)
* Vector and Hashtable (extends Dictionary) are older collection classes.
- Vector has been made to extend AbstractList and is like a sync'd
ArrayList (maha:set)z.
- Hashtable still extends Dictionary but it implements Map.
- In contrast to other collection types, Vector and Hashtable are
synchronized.
* Vector和Hashtable(继承自Dictionary)是较老的集合类
- Vector继承自AbstractList,与同步的ArrayList相像
- Hashtable仍然继承自Dictionary但是实现了Map接口
- 与其他集合类型相比较,Vector和Hashtable是同步的
* There are Collections and Arrays classes to provide static methods for
general algorithms on collections and arrays.
* Collection和Array都提供了静态的方法处理集合和数组的运算
* Stack extends Vector
- it has methods push(Object), pop, peek and search(Object).
- Push is identical to addElement but also returns the added Object.
- The top of a stack is the last element in the vector (and has index 1 as
far as the search method is concerned).
* Stack继承自Vector
- 方法:push(Object),pop,peek和search(Object)
- push方法与addElement的效果相似,同时返回刚刚添加过的对象
- 栈顶是Vector里面最后一个元素(search方法将返回1)
------------------------------------------------------------------------
Math methods
Math的方法
* most act on and return double values
- note that floor(double), ceil(double) and rint(double) return doubles
not ints
* 大部分的方法都是对double类型数据作处理并返回double型的结果
- 注意floor(double),ceil(double)和rint(double)返回的是double类型而不
是int
* abs, max and min can take double, float, int or long arguments and the
return type matches the argument type.
* abs,max和min方法可以处理double,float,int或者long型的参数并且返回与
参数类型一样的返回值
* There are three rounding methods:
- int round( float ); // note both are 32-bit
- long round( double ); // note both are 64-bit
- double rint( double );
* 三个取整方法:
- int round(float); // 注意两者都是32位
- long round(double); // 注意两者都是64位
- double rint(double);
* log returns natural log.
* log方法返回自然对数
* trig functions take double arguments in radians.
* trig函数的参数是double型的弧度
------------------------------------------------------------------------
------------------------------------------------------------------------
AWT
抽象窗口工具包
* Component is abstract ... Container is not abstract.
* Component是抽象的 … Container不是抽象的
* Checkbox has 5 ctors: no-arg + four with String as first arg and
combinations of boolean initialState and CheckboxGroup.
* Checkbox有五个构造函数:一个没有任何参数,其他四个都以字符串为第一个参
数,以及boolean型的初始化状态、CheckboxGroup
* CheckboxMenuItem has nothing to do with Checkbox or CheckboxGroup.
- i think they generate both Item- and ActionEvents.
* CheckboxMenuItem与Checkbox和CheckboxGroup没有任何关系
- 我想他们都产生ItemEvent和ActionEvent
* Listeners:
- InputEvent (super for MouseEvent and KeyEvent) has a 'long getWhen()'
method.
- MouseEvent has 'int getX', 'int getY' and 'Point getPoint' methods.
- ActionEvent and ItemEvent are not ComponentEvents so have to use
getSource().
- MenuItems (inc. menus) can produce ActionEvents but not ItemEvents.
- ActionListener,Adjustment, ItemListener and TextListener only have
one method and therefore don't have Adapters.
- KeyListener: Pressed/Released/Typed
- FocusListener: Lost/Gained
- ComponentListener: Shown/Hidden Moved Resized
- ContainerListener: component- Added/Removed
- WindowListener: Opened/Closing/Closed
Activated/Deactivated ... keyboard focus.
Iconifed/Deiconified
- MouseListener: Pressed/Released/Clicked
Entered/Exited
- MouseMotionListener: Dragged/Moved
* 接收器:
- InputEvent(MouseEvent和KeyEvent的父类)有方法:long getWhen()
- MouseEvent的方法:int getX,int getY,Point getPoint
- ActionEvent和ItemEvent不属于ComponentEvent,只能使用getSource()
- MenuItem(例如菜单)产生的是ActionEvent而不是ItemEvent
- ActionListener,Adjustment,ItemListener和TextListener只定义了一个方法
,所以不需要适配器
- KeyListener:键的按下/释放/敲击
- FocusListener: 焦点的失去/获得
- ComponentListener: 显示/隐藏,移动,改变大小
- ContainerListener: 添加/删除组件
- WindowListener: 打开/关闭中/已经关闭
激活/无效 ... 键盘焦点
最小化/恢复
- MouseListener: 键的按下/释放/点击
鼠标进入/退出
- MouseMotionListener: 拖动/移动
------------------------------------------------------------------------
Layout
布局
* BorderLayout is the default layout for Window/Frame/Dialog.
- add( component, BorderLayout.NORTH ) == add( "North", component )
- adding a component without an explicit position is identical to
adding a component at BorderLayout.CENTER.
- if more than one component is added to the same position, the most
recently added component is displayed there.
- north,south,east and west components only expand on one axis.
* BorderLayout是Window/Frame/Dialog的默 喜季 管理器
- add(component,BorderLayout.NORTH) == add("North",component)
- 如果不说明位置,组件将按默认的设置添加到CENTER的位置
- 如果超过一个组件添加到一个位置上,最后添加的将被显示
- north,south,east和west上的组件只在一个方向上延伸
* FlowLayout is the default layout for Panels (including Applets).
- if the panel is bigger than its components, they are centered
horizontally and at the top (ie. north position).
* Panel(包括Applet)的默 喜季 管理器是FlowLayout
- 如果panel比组件大,组件将被水平居中并置于顶端
* GridLayout with container larger than components expands to fill its
container provided that the number of components matches the
rows*columns.
- Empty rows are given space, while empty cols are not.
- If there aren't enough components, it will try to fill its rows first.
* 当GridLayout的容器比组件大时,组件将被扩充到填满整个容器,需要提供
rows*columns个组件
- 空行将被分配空间,但时空列不分配空间
- 如果组建的数目不够,首先尝试填充所有的行
* Ctors for BorderFlow- and GridLayout can take int hgap and vgap args.
- FlowLayout(int align, hgap, vgap)
* BorderFlow以及GridLayout的构造函数可以带参数hgap和vgap
- FlowLayout(int align, hgap, vgap)
* Be careful with nested layout questions ... eg Button to panel to frame,
the panel fills the whole frame, but the button will be its preferred size
at north position in the panel (and thus the frame).
* 对嵌套的布局管理器要小心 … 例如一个frame包含一个panel,panel包含一个
Button,panel填充整个frame,但是button仍然只有预定的大小,位于frame的
北面
* GridBagLayout
- There are two ways to set the constraints for a component in a gbl:
container.add( Component c, Object gbc ) or
gbl.setConstraints( Component c, GridBagConstraints gbc )
- weightx and weighty are doubles (0 to maxDouble, default 0) and determine
where extra width or height is added if a row or column is smaller than
the container.
- gridwidth and gridheight are ints (1 to maxInt) ... RELATIVE, REMAINDER.
- gridx and gridy are ints (0 to maxInt) ... RELATIVE
- RELATIVE can apply to gridx/gridy (=next) or
gridwidth/gridheight (=second last)
* GridBagLayout
- 有两种方法可以将一个组件使用constraints添加到GridBagLayout中去:
container.add(Component c,Object gbc) 或者
gbl.setConstraints(Component c,GridBagConstraints gbc)
- weightx和weighty是double类型(0到maxDouble,默认是0)的属性,它们决
定额外的宽度或者高度是否添加到当前的行或者列
- gridwidth和gridheight是整型的数据类型(从1到maxInt) … 相对的,剩余
的
- gridx和gridy是整型的(从0到maxInt) … 相对的
- …
* A Component added to a layout won't display unless you set its
bounds ... this is the only place where a component can control its
parent's layout directly.
* 如果将一个组件添加到一个空的布局管理器中,只有设置组件的范围才能够显示
* Illegal arguments (eg. adding a container's parent to the container, adding
a window) get through the compiler but throw an exception at runtime.
* 不正确的参数(例如,添加一个容器的容器到自身,添加一个window)可以通过
编译,但是将会在运行期间抛出异常
------------------------------------------------------------------------
------------------------------------------------------------------------
Miscellaneous
杂锦
* A class type's name is valid as an identifier, eg. int Boolean = 5;
* Modifiers:
- Automatic variable = local variable = variable declared in a method.
- Transient fields are not written out when a class is serialized.
- Transient and Volatile can only be applied to fields.
- Native can only be applied to methods.
- You can have a static synchronized method .. it is synchronized on the
class object.
- static transient is legal but doesn't effect anything.
* 一个类的名称是合法的标识名,例如:int Boolean = 5;
* 修饰符:
- …
- 当序列化一个类时,以transient修饰的字段不会写进数据流
- transient和volatile只能修饰字段
- native修饰符只能用于方法
- 可以有同步的静态方法,它使用类对象作为同步锁
- static transient是合法的,但是并不去起作用
* The right-hand-side of an assignment can be a reference to .
- You can println a reference (and add it to another string).
- What you can't do with a reference is ... Ref.aMethod();
* 赋值操作的右侧可以是
- 可是打印空的引用(还可以赋给一个字符串变量)
- 你不能做的是 … Ref.aMethod();
*
1. ++,--,unary +,unary -,~,!,()
2. *,/,%
3. +,- 4. >>, >>>, <<
5. >, >=, <, <=, instanceof
6. == , !=
7. &
8. ^
9. |
10 &&
11 ||
12 ? : 13 =,+=,-=,*=,/=,%=, &=,^=,|=, >>= ,<<= ,>>>=
* Order of Operation
- arithmetic before &^|
- & then ^ then |
* 运算顺序
- 先数学运算,后&^|
- 先&然后^最后|
* Garbage Collection
- unreachable objects can become reachable (if their finalize method
causes another object to have a reference to them) .. but i think
finalize if guaranteed to not run again.
- objects referenced by block-level variables are probably not available
for garbage collection until their enclosing method's scope is exited.
* 内存回收
- …
- …
* The compiler never object to creating a local instance of the
the class being constructed in its constructor. If the call produces
an infinite loop, a runtime error will occur.
* 编译器从不反对在构造函数中创建一个本类的实例,但是如果这导致无限的循环
,一个运行期间的错误将会被抛出
* Labelled break and continue statements:
- The label referred to by a labelled break statement is attached to
a statement block, which could be a loop or switch but doesnt have
to be.
- The label referred to by a labelled continue statement must be
attached to a loop.(A "continue" statement must be enclosed in a "while",
"do" or "for" statement.)
* 带标号的break和continue声明
- 带标号的break可用于标识循环和开关语句,但不是必须的
- 带标号的continue只能用于循环语句(continue必须出现在while、do或者
for子句中)
------------------------------------------------------------------------
------------------------------------------------------------------------
Things to look out for
*** Read the answers before going through code samples.
****** LOOK FOR NON-STATIC METHODS/VARS ACCESSED FROM MAIN
****** WHEN YOU FINISH THE EXAM GO BACK AND CHECK FOR NON-STATIC
METHODS/VARS FROM MAIN AND OTHER STATIC METHODS
* if (...)
statement1;
statement2; //...always executed
* Beware of an otherwise legal override having a more restrictive
access modifier.
* Beware of missing return statements.
* Look for static modifiers and make sure they don't contain refs to
instance vars.
* Beware of standard methods (eg. main, paint, run) with the wrong
args or return type.
* With array declarations, look out for "int intArray[5] = ..."
* Beware of adding a primitive to a Vector.
- more generally, you can't use a primitive where an Object is
required (eg. the equals method).
* System.out.println( aReferenceToNull ); // is fine
* Beware of local vars from a try block used in its catch block
(out of scope).
需要留意的
*** 先读答案在看代码段
****** 寻找在main中调用的非静态的变量和方法
****** 当你完成考试时,回头检查main和其他静态方法中的非静态变量和方法调用
* if (...)
statement1;
statement2; //...总是运行
* 留意那些合法的方法覆盖,即使它们的权限变小
* 留意没有返回值的方法
* 保证静态代码不能引用类实例变量
* 留意标准方法(例如,main,print和run)的不正确的参数类型和返回值
* 数组声明,留意形如"int intArray[5] = ..."的语句
* 小心不要将基本类型添加到Vector中
- 更普遍的情况,当需要用Object的时候不要用基本类型(例如equals方法)
* System.out.println( aReferenceToNull ); // 代码将运行得很好
* 小心不要在catch中使用try中定义的局部变量(超出范围)