泛型
-
问题: Collection元素类型
- 编译器无法帮助验证类型
- 赋值必须进行强制类型转换
- 有可能产生运行时的错误(ClassCastException)
-
解决办法:
- 告诉编译器元素类型
- 让编译器来做类型的匹配和转换
- 保证运行成功
使用泛型修饰的对象:
-
创建与特定类型关联的泛型对象实例:
Vector x = new Vector();
x.add(new Integer(5)); // 编译器错误 -
类型变量定义在<>之间
- 不同类型变量之间用逗号分隔
Core Java
第一章 Java程序设计概述
- Java程序设计平台
- Java发展简史
- Java与“白皮书”关键术语
简单些、可移植性、面向对象、解释型、分布式、高性能、
健壮性、多线程、安全性、动态性、体系结构中立 - Java与Internet
第二章 Java程序设计环境
- 安装Java开发工具箱
- 选择开发环境
- 使用命令行工具
- 使用集成开发环境
- 使用文本编辑器编译并运行程序
- 使用图形化应用程序
- 建立并运行applet
第三章 Java基本的程序设计结构
-
一个简单的Java应用程序
Java对大小写敏感;
Java中定义类名的规则很宽松。名字必须以字母开头,后面可以跟字母和数字的任意组合。长度基本上没有限制。
但是不能使用Java保留字。
标准的命名规范为:类名是以大写字母开头的名词。如果名字有多个单词组成,每个单词的第一个字母都应为大写。
源代码的文件必须与公有类的名字相同,并用.java作为扩展名。
已经正确命名了文件并且源代码中没有任何录入错误,那么在编译源代码之后就会得到一个包含该类字节码的文件。Java编译器将字节码文件自动地命名为FirstSample.class,并与源文件存储在同一个目录下。
运行编译程序时,Java虚拟机将从指定类中的main方法开始执行,因此为了代码能够得到执行,在类的源文件中必须包含一个main方法。
根据Java语言规范,main方法必须被声明为public。
Java中每个句子都必须用分号结束。 -
注释
在Java中,有三种表示注释的方式。最常用的方式是使用//,其注释内容从//开始到本行结尾。
当需要比较长的注释时,可以在每行的注释前面标记//,也可以使用/*和*/将一段比较长的注释括起来。
第三种注释可以用来自动地声称文档。这种注释以/**开始,以*/结束。
警告:在Java中,/*/注释不能嵌套。也就是说,如果代码本省包含了一个\/,就不能用/*和*/将注释括起来。 - 数据类型
Java是一种强类型语言(strongly typed language)。这就意味着必须为每一个变量声明一种类型。
在Java中一共有8种基本类型(primitive type),其中有4个整型、2个浮点类型、1个用于表示Unicode编码的字符单元的字符类型char和1个用于表示真值的boolean类型。 注意:Java有一个能够表示任意精度的算书包,通常称为“大数值”(big number)。虽然名字被称为大数值,但它并不是一种新的Java类型,而是一个Java对象。- 3.3.1 整型
- 整型用于表示没有小数部分的数值,它允许是负数。Java提供了4种整型,如图所示:
- byte和short类型主要用于特定的场合,例如:底层的文件处理和需要控制占用存储空间量的大数组
- 长整型数值有一个后缀L,十六进制有一个前缀0x,八进制有一个前缀0
-
类型 存储需求 取值范围 int 4字节 -2147483648~2147483647 short 2字节 -32768~32767 long 8字节 -9223372036854775808~9223372036854775808 byte 1字节 -128~127
- 3.3.2 浮点型
- Java有两种浮点类型,具体如表所示:
- double表示这种类型的数值精度是float的两倍(有人称之为双精度)
- float类型的数值默认有一个后缀F,没有后缀F的浮点类型默认为double类型
- 在JDK5.0中可以使用十六进制表示浮点数值。例如,0.125可以表示为0x1.0p-3。在十六进制中使用p表示指数而不是e
- 所有的浮点数值都遵循IEEE754规范。下面是三个特殊的浮点数值:
- 正无穷大
- 负无穷大
- NaN
- 注意:常量Double.POSITIVE_INFINITY、Double.NEGATIVE_INFINITY,和Double.NAN(与相应的float类型的常量一样)分别表示这三个特殊的值,但在实际应用中很少会遇到。特别要说明的是,不能够这样测试:if(x==DOUBLE.NAN)//it's never true 用于检测一个特定的值是否等于DOUBLE.NAN。所有非数值的值都会被认为是不相同的。然而可以使用Double.isNAN方法:if(Double.isNan(x))//check whether x is not a number
-
类型 存储需求 取值范围 float 4字节 大约+-3.40282347E+38F(有效位数为6~7位) double 8字节 大约+-1.79769313485231570E+308(有效位数为15位)
- 3.3.3 char类型
- Besides the \u escape sequences that indicate the encoding of Unicode code units, there
are several escape sequences for special characters, as shown in Table 3–3. - Table 3–3 Escape Sequences for Special Characters
Escape Sequence Name Unicode Value \b Backspace \u0008 \t Tab \u0009 \n Linefeed \u000a \r Carriage return \u000d \" Double quote \u0022 \' Single quote \u0027 \\ Backslash \u005c
- A particular code value
corresponds to different letters in the various encoding schemes. Moreover, the encodings
for languages with large character sets have variable length: Some common characters
are encoded as single bytes, others require two or more bytes.Unicode was designed to solve these problems。 - A code point is a code value that is associated with a character in
an encoding scheme. In the Unicode standard, code points are written in hexadecimal
and prefixed with U+, such as U+0041 for the code point of the letter A. Unicode has
code points that are grouped into 17 code planes. The first code plane, called the basic
multilingual plane, consists of the “classic” Unicode characters with code points U+0000
to U+FFFF. Sixteen additional planes, with code points U+10000 to U+10FFFF, hold the
supplementary characters.
The UTF-16 encoding is a method of representing all Unicode code points in a variablelength
code. The characters in the basic multilingual plane are represented as 16-bit
values, called code units. - In Java, the char type describes a code unit in the UTF-16 encoding.
Our strong recommendation is not to use the char type in your programs unless you are
actually manipulating UTF-16 code units. You are almost always better off treating
strings (which we will discuss in the section “Strings” on page 53) as abstract data types.
- Besides the \u escape sequences that indicate the encoding of Unicode code units, there
- 3.3.4 The boolean Type
The boolean type has two values, false and true. It is used for evaluating logical conditions.
You cannot convert between integers and boolean values.- C++ NOTE: In C++, numbers and even pointers can be used in place of boolean values. The
value 0 is equivalent to the bool value false, and a non-zero value is equivalent to true.
- C++ NOTE: In C++, numbers and even pointers can be used in place of boolean values. The
- 3.3.1 整型
- 变量
- Notice the semicolon at the end of each declaration. The semicolon is necessary because
a declaration is a complete Java statement.
A variable name must begin with a letter and must be a sequence of letters or digits. Note
that the terms “letter” and “digit” are much broader in Java than in most languages.- All characters in the name of a variable are significant and case is also significant. The length of
a variable name is essentially unlimited. - TIP: If you are really curious as to what Unicode characters are “letters” as far as Java is
concerned, you can use the isJavaIdentifierStart and isJavaIdentifierPart methods in the
Character class to check. - You also cannot use a Java reserved word for a variable name.
- You can have multiple declarations on a single line:
int i, j; // both are integers
However, we don’t recommend this style. If you declare each variable separately, your
programs are easier to read.
- All characters in the name of a variable are significant and case is also significant. The length of
- Initializing Variables
- After you declare a variable, you must explicitly initialize it by means of an assignment
statement—you can never use the values of uninitialized variables. - Finally, in Java you can put declarations anywhere in your code. For example, the following
is valid code in Java:
double salary = 65000.0;
System.out.println(salary);
int vacationDays = 12; // ok to declare a variable here
In Java, it is considered good style to declare variables as closely as possible to the point
where they are first used. - C++ NOTE: C and C++ distinguish between the declaration and definition of variables. For
example,
int i = 10;
is a definition, whereas
extern int i;
is a declaration. In Java, no declarations are separate from definitions.
- After you declare a variable, you must explicitly initialize it by means of an assignment
- Constants
In Java, you use the keyword final to denote a constant.- The keyword final indicates that you can assign to the variable once, and then its value
is set once and for all. It is customary to name constants in all uppercase。 - It is probably more common in Java to want a constant that is available to multiple
methods inside a single class. These are usually called class constants. You set up a class
constant with the keywords static final. - C++ NOTE: const is a reserved Java keyword, but it is not currently used for anything. You
must use final for a constant.
- The keyword final indicates that you can assign to the variable once, and then its value
- Operators
- Notice the semicolon at the end of each declaration. The semicolon is necessary because
- 运算符
-
-
- The usual arithmetic operators + – * / are used in Java for addition, subtraction, multiplication,
and division. The / operator denotes integer division if both arguments are
integers, and floating-point division otherwise. Integer remainder (sometimes called
modulus) is denoted by %. - Note that integer division by 0 raises an exception, whereas floating-point division
by 0 yields an infinite or NaN result. - the initial specification of the Java virtual machine mandated
that all intermediate computations must be truncated. The numeric community hated
it. Not only can the truncated computations cause overflow, they are actually slower than the
more precise computations because the truncation operations take time. For that reason,
the Java programming language was updated to recognize the conflicting demands for optimum
performance and perfect reproducibility. By default, virtual machine designers are now
permitted to use extended precision for intermediate computations. However, methods
tagged with the strictfp keyword must use strict floating-point operations that yield reproducible
results. For example, you can tag main as
public static strictfp void main(String[] args)
Then all instructions inside the main method use strict floating-point computations. If you tag
a class as strictfp, then all of its methods use strict floating-point computations.
- The usual arithmetic operators + – * / are used in Java for addition, subtraction, multiplication,
- Increment and Decrement Operators
- Programmers, of course, know that one of the most common operations with a numeric
variable is to add or subtract 1. Java, following in the footsteps of C and C++, has both
increment and decrement operators: n++ adds 1 to the current value of the variable n, and
n-- subtracts 1 from it. - We recommend against using ++ inside other expressions because this often leads to confusing
code and annoying bugs.
- Programmers, of course, know that one of the most common operations with a numeric
- Relational and boolean Operators
- Java has the full complement of relational operators. To test for equality you use a double
equal sign, ==.Finally, you have the usual < (less than), > (greater than), <= (less than or equal), and >=
(greater than or equal) operators.
Java, following C++, uses && for the logical “and” operator and || for the logical “or”
operator. As you can easily remember from the != operator, the exclamation point ! is the
logical negation operator. The && and || operators are evaluated in “short circuit” fashion.
The second argument is not evaluated if the first argument already determines the
value.Similarly, the value of expression1 || expression2 is automatically true if the first expression
is true, without evaluation of the second expression. - Finally, Java supports the ternary ?: operator that is occasionally useful. The expression
condition ? expression1 : expression2
evaluates to the first expression if the condition is true, to the second expression otherwise.
For example,
x < y ? x : y
gives the smaller of x and y.
- Java has the full complement of relational operators. To test for equality you use a double
- Bitwise Operators
When working with any of the integer types, you have operators that can work
directly with the bits that make up the integers. This means that you can use masking
techniques to get at individual bits in a number. The bitwise operators are
& (“and”) | (“or”) ^ (“xor”) ~ (“not”)
These operators work on bit patterns. For example, if n is an integer variable, then
int fourthBitFromRight = (n & 8) / 8;
gives you a 1 if the fourth bit from the right in the binary representation of n is 1, and 0 if
not. Using & with the appropriate power of 2 lets you mask out all but a single bit。- NOTE: When applied to boolean values, the & and | operators yield a boolean value. These
operators are similar to the && and || operators, except that the & and | operators are not
evaluated in “short circuit” fashion. That is, both arguments are first evaluated before the
result is computed. - There are also >> and << operators, which shift a bit pattern to the right or left. These
operators are often convenient when you need to build up bit patterns to do bit
masking:
int fourthBitFromRight = (n & (1 << 3)) >> 3;
Finally, a >>> operator fills the top bits with zero, whereas >> extends the sign bit into the
top bits. There is no <<< operator. - CAUTION: The right-hand side argument of the shift operators is reduced modulo 32
(unless the left-hand side is a long, in which case the right-hand side is reduced modulo 64).
For example, the value of 1 << 35 is the same as 1 << 3 or 8. - C++ NOTE: In C/C++, there is no guarantee as to whether >> performs an arithmetic shift
(extending the sign bit) or a logical shift (filling in with zeroes). Implementors are free to
choose whatever is more efficient. That means the C/C++ >> operator is really only defined
for non-negative numbers. Java removes that ambiguity.
- NOTE: When applied to boolean values, the & and | operators yield a boolean value. These
- Mathematical Functions and Constants
- NOTE: There is a subtle difference between the println method and the sqrt method. The
println method operates on an object, System.out, defined in the System class. But the sqrt
method in the Math class does not operate on any object. Such a method is called a static
method. You can learn more about static methods in Chapter 4 - TIP: Starting with Java SE 5.0, you can avoid the Math prefix for the mathematical methods
and constants by adding the following line to the top of your source file:
import static java.lang.Math.*;
For example:
System.out.println("The square root of \u03C0 is " + sqrt(PI));
We discuss static imports in Chapter 4. - NOTE: The functions in the Math class use the routines in the computer’s floating-point
unit for fastest performance. If completely predictable results are more important than
fast performance, use the StrictMath class instead. It implements the algorithms from the
“Freely Distributable Math Library” fdlibm, guaranteeing identical results on all platforms.
See http://www.netlib.org/fdlibm/index.html for the source of these algorithms. (Whenever
fdlibm provides more than one definition for a function, the StrictMath class follows the
IEEE 754 version whose name starts with an “e”.)
- NOTE: There is a subtle difference between the println method and the sqrt method. The
- Conversions between Numeric Types
- The six solid arrows in Figure 3–1 denote conversions without information loss. The
three dotted arrows denote conversions that may lose precision. - When two values with a binary operator (such as n + f where n is an integer and f is a
floating-point value) are combined, both operands are converted to a common type
before the operation is carried out.
• If either of the operands is of type double, the other one will be converted to a double.
• Otherwise, if either of the operands is of type float, the other one will be converted
to a float.
• Otherwise, if either of the operands is of type long, the other one will be converted
to a long.
• Otherwise, both operands will be converted to an int.
- The six solid arrows in Figure 3–1 denote conversions without information loss. The
- Casts
- Numeric conversions are possible in Java, but of course
information may be lost. Conversions in which loss of information is possible are done
by means of casts.The syntax for casting is to give the target type in parentheses, followed
by the variable name. - If you want to round a floating-point number to the nearest integer (which is the more useful
operation in most cases), use the Math.round method:
double x = 9.997;
int nx = (int) Math.round(x); Now the variable nx has the value 10. You still need to use the cast (int) when you
call round. The reason is that the return value of the round method is a long, and a long
can only be assigned to an int with an explicit cast because there is the possibility
of information loss. - CAUTION: If you try to cast a number of one type to another that is out of the range for the
target type, the result will be a truncated number that has a different value. For example,
(byte) 300 is actually 44. - C++ NOTE: You cannot cast between boolean values and any numeric type. This convention
prevents common errors. In the rare case that you want to convert a boolean value to a number,
you can use a conditional expression such as b ? 1 : 0.
- Numeric conversions are possible in Java, but of course
- Parentheses and Operator Hierarchy
- Table 3–4 on the following page shows the precedence of operators. If no parentheses
are used, operations are performed in the hierarchical order indicated. Operators on the
same level are processed from left to right, except for those that are right associative, as
indicated in the table.For example, because && has a higher precedence than ||, the
expression
a && b || c
means
(a && b) || c
Because += associates right to left, the expression
a += b += c
means
a += (b += c)
That is, the value of b += c (which is the value of b after the addition) is added to a.
C++ NOTE: Unlike C or C++, Java does not have a comma operator. However, you can use
a comma-separated list of expressions in the first and third slot of a for statement. - Table 3–4 Operator Precedence
-
Operators Associativity [] . () (method call) Left to right ! ~ ++ -- + (unary) – (unary) () (cast) new Right to left * / % Left to right + - Left to right << >> >>> Left to right < <= > >= instanceof Left to right == != Left to right & Left to right ^ Left to right | Left to right && Left to right || Left to right ?: Right to left = += -= *= /= %= &= |= ^= <<= >>= >>>= Right to left
-
- Table 3–4 on the following page shows the precedence of operators. If no parentheses
- Enumerated Types
- Sometimes, a variable should only hold a restricted set of values.
- A variable of type Size can hold only one of the values listed in the type declaration or
the special value null that indicates that the variable is not set to any value at all.
-
-
- 字符串
- Sometimes, a variable should only hold a restricted set of values.Java does not have a
built-in string type. Instead, the standard Java library contains a predefined class called,
naturally enough, String. Each quoted string is an instance of the String class - Substrings
- Concatenation
- Java, like most programming languages, allows you to use the + sign to join (concatenate)
two strings.When you concatenate a string with a value that is not a string, the latter is converted
to a string. - Strings Are Immutable
- The String class gives no methods that let you change a character in an existing string. If
you want to turn greeting into "Help!", you cannot directly change the last positions of greeting
into 'p' and '!'. If you are a C programmer, this will make you feel pretty helpless.
How are you going to modify the string? In Java, it is quite easy: Concatenate the substring
that you want to keep with the characters that you want to replace.
greeting = greeting.substring(0, 3) + "p!";
This declaration changes the current value of the greeting variable to "Help!".Because you cannot change the individual characters in a Java string, the documentation
refers to the objects of the String class as being immutable. Just as the number 3 is
always 3, the string "Hello" will always contain the code unit sequence describing the
characters H, e, l, l, o. You cannot change these values. You can, as you just saw however,
change the contents of the string variable greeting and make it refer to a different
string, just as you can make a numeric variable currently holding the value 3 hold the
value 4.Isn’t that a lot less efficient? It would seem simpler to change the code units than to
build up a whole new string from scratch. Well, yes and no. Indeed, it isn’t efficient to
generate a new string that holds the concatenation of "Hel" and "p!". But immutable
strings have one great advantage: the compiler can arrange that strings are shared.Overall, the designers of Java decided that the efficiency of sharing outweighs the inefficiency
of string editing by extracting substrings and concatenating. Look at your own
programs; we suspect that most of the time, you don’t change strings—you just compare
them. (There is one common exception—assembling strings from individual characters
or shorter strings that come from the keyboard or a file. For these situations, Java
provides a separate class that we describe in the section “Building Strings” on page 62.)C++ NOTE: C programmers generally are bewildered when they see Java strings for the first
time because they think of strings as arrays of characters:
char greeting[] = "Hello";
That is the wrong analogy: A Java string is roughly analogous to a char* pointer,
char* greeting = "Hello";
When you replace greeting with another string, the Java code does roughly the following:
char* temp = malloc(6);
strncpy(temp, greeting, 3);
strncpy(temp + 3, "p!", 3);
greeting = temp;
Sure, now greeting points to the string "Help!". And even the most hardened C programmer
must admit that the Java syntax is more pleasant than a sequence of strncpy calls. But what
if we make another assignment to greeting?
greeting = "Howdy";
Don’t we have a memory leak? After all, the original string was allocated on the heap. Fortunately,
Java does automatic garbage collection. If a block of memory is no longer
needed, it will eventually be recycled.
If you are a C++ programmer and use the string class defined by ANSI C++, you will be much
more comfortable with the Java String type. C++ string objects also perform automatic allocation
and deallocation of memory. The memory management is performed explicitly by constructors,
assignment operators, and destructors. However, C++ strings are mutable—you can
modify individual characters in a string. - Testing Strings for Equality
- can be string
variables or string constants、equalsIgnoreCase method、Do not use the == operator to test whether two strings are equal! It only determines
whether or not the strings are stored in the same location. - Code Points and Code Units
- Java strings are implemented as sequences of char values.、The length method yields the number of code units required for a given string in the
UTF-16 encoding.、To get the true length, that is, the number of code points, call
int cpCount = greeting.codePointCount(0, greeting.length());、Why are we making a fuss about code units? Consider the sentence
is the set of integers
The character requires two code units in the UTF-16 encoding. Calling
char ch = sentence.charAt(1)
doesn’t return a space but the second code unit of . To avoid this problem, you should
not use the char type. It is too low-level.、If your code traverses a string, and you want to look at each code point in turn, use
these statements:
int cp = sentence.codePointAt(i);
if (Character.isSupplementaryCodePoint(cp)) i += 2;
else i++;、Fortunately, the codePointAt method can tell whether a code unit is the first or second half
of a supplementary character, and it returns the right result either way. That is, you can
move backwards with the following statements:
i--;
int cp = sentence.codePointAt(i);
if (Character.isSupplementaryCodePoint(cp)) i--; - The String API
- Building Strings
- Occasionally, you need to build up strings from shorter strings, such as keystrokes or
words from a file. It would be inefficient to use string concatenation for this purpose.
Every time you concatenate strings, a new String object is constructed. This is time consuming
and it wastes memory. Using the StringBuilder class avoids this problem.、
- Sometimes, a variable should only hold a restricted set of values.Java does not have a
- 输入输出
- 控制流程
- 大数值
- 数组
-