
Java编程思想第4版(评注版)
《Java编程思想第4版(评注版)》是2011年电子工业出版社出版的图书。作者是埃克尔,刘中兵评注。《Java编程思想(评注版第4版)》是“传世经典书丛”之一,作者拥有多年教学经验,对C、C++以及Java语言都有独到、深入的见解,书中以通俗易懂且小而直接的示例阐释了一个个晦涩抽象的概念,是一本当之无愧的经典之作,书中包括基本语法、面向对象、高级特性等五部分内容。本书适合从事相关研究工作的人员参考阅读。
基本介绍
- 书名:Java编程思想第4版(评注版)
- 作者:(美)埃克尔(Eckel, B.)、刘中兵
- ISBN:978-7-121-13521-7
- 页数:756页
- 定价:108.00元
- 出版社:电子工业出版社
- 出版时间:2011年6月
- 开本:16开
内 容 简 介
本书作者拥有多年教学经验,对C、C++以及Java语言都有独到、深入的见解,书中以通俗易懂且小而直接的示例阐释了一个个晦涩抽象的概念,是一本当之无愧的经典之作。本评注版讲解了Java设计、语法和库的各个方面,包括Java的运算符、控制逻辑、构造、回收、重用、接口、内部类、存储、异常、字元串、类型、泛型、数组、容器、I/O、注释、并发等内容。
对于国外技术图书,选择翻译版还是影印版,常常让人陷入两难的境地。本评注版力邀国内资深专家执笔,在英文原着基础上增加中文点评与注释,旨在融合二者之长,既保留经典的原创文字与味道,又以先行者的学研心得与实践感悟,对读者阅读与学习加以点拨、指明捷径。
经过评注的版本,更值得反覆阅读与体会。希望这本书能够帮助您跨越Java的重重险阻,领略高处才有的壮美风光,做一个成功而快乐的Java程式设计师。
评注者序
与Thinking in Java的渊源
学习Java的道路好比西天取经,Java就是要取得的真经,我们都是去往Java之路的圣徒。
学习Java不仅要经历九九八十一难,更要理解Java这本圣经的精髓。大家都觉得Java之路不好走,因为它不仅仅是Java,还有无数的技术,如JSP、Servlet、JavaBean、J2EE、Struts、Spring、Hibernate、资料库SQL、SOA分散式、快取、JVM、Eclipse、Tomcat、HTTP、JSON等等,它们组成了取经道路上的九九八十一难。众多技术,围绕的精髓是Java。
在学习Java的道路上,我也经历过九九八十一难。我通过编写《Java高手真经》对Java道路上的层层技术做了一个自认为完整的总结,也是对自己步入Java世界以来的种种所见所闻所感的记录和升华。但此时,对Java我有种被掏空的感觉。因为,我觉得自己对Java的精髓理解得还是不够。
偶然的机会接到博文视点的邀约,为这本《Java编程思想》(Thinking in Java)的英文版本做点评。儘管我写过很多技术类的书,但对于这种圣经式的经典着作,借用时下最流行的一句话,内心有一点“忐忑”。因为,对经典着作做的点评,必须是点睛之笔,对原文要能够画龙点睛。想到这里,内心就更加忐忑了!为此,我抱着学习交流的心态重读了这本书。
刚学习Java时,往往会经资深人士推荐说:“读这本《Java编程思想》才是学真正的Java,国人所着太浅!”于是怀着崇拜之情,读之,傻眼,1000多页、大量本质的分析,再加上蹩脚的英语,读之皮毛矣!从此也就束之高阁。
何时应该读这本书
李彦宏关于网际网路的发展曾说过:“时机很重要,进去太早会饿死,太晚就没有机会了。”实际上这句话在这里也适用,太早读这本书会难以理解,太晚你会后悔为什幺才看到这本书。这是因为,正如书名所言,它讲解的是Java编程的内在思想,只有拥有了一定Java编程基础和开发经验后,读它才是对Java理解的升华!
因此,这本书最大的作用不是让你“知其然”,而是让你“知其所以然”!
如何读这本书
本书原英文版涵盖了Java设计、语法和库的各个方面,包括Java的运算符、控制逻辑、构造、回收、重用、多态、接口、内部类、存储、异常、字元串、类型、泛型、数组、容器、I/O、注释、并发、图形GUI。原英文版是按美国人的习惯散列排列的,本书为了更加一目了然,更加符合国人的思维方式,将这些章节分为五个大的部分,每一部分都涵盖了深入分析的独家内容。
第1部分 基本语法:运算符、控制逻辑
运算符和控制逻辑是任何一门语言的最基础语法,Java参考了C++的优点,扬长避短,因此它的运算符也基于C++,但在某些方面进行了简化和改进。熟悉C++将会对本部分轻车熟路。Java中的控制语句共提供了如下几个关键字:if/else/while/do-while/for/return/break/continue/switch。虽然有goto,但是不要使用,它会使代码混乱。在Java中已经摒弃了goto语句。
第2部分 面向对象:对象的创建与销毁、访问控制、重用、接口、内部类、异常
本书是关于类的初始化和销毁讲解最为完美的一本书,细緻、全面、易懂。访问控制专门开闢了一章,对于类和包的访问控制关係讲解小巧到位。要让每个人编写的程式能够为他人所用,首先是类的包结构清晰,其次是代码中的函式包装清晰。
第3部分 数据存储:字元串、数组、存储、容器
java.util包中提供了纷繁複杂的容器类,包括集合类Collection(包括Queue先进先出伫列、List允许重複的有序列表、Set不允许重複的集合)和映射类Map(键值对)。本书深度分析了基于这些接口的各种实现类的使用、工作原理。“Containers in Depth”一章是讲解Java容器类最深入的部分,它会告诉你何时应该使用哪些容器、哪些是最有用的、为什幺使用以及怎幺使用。
第4部分 核心功能:输入输出、并发
I/O提供了Java与外部系统进行通信的基础库,包括控制台、档案、网路。这些是I/O需要涉及的方方面面。输入输出的方式包括顺序读取、随机读取、快取、二进制、字元、行读取、位元组读取等等,因此I/O也提供了各种读写的包装类。本书通过大量实例来演示这些类的使用方法和套用场景。
多执行绪是与单执行绪比较而言的,本书从基本的Thread、Runnable的使用讲起,深入且全面讲解了执行绪的休眠、优先权、Daemon、执行绪的异常处理、资源共享、执行绪的控制、与其他执行绪的协作、死锁等,并讲解了Java中使用的一些执行绪工具类。
第5部分 高级特性:类型、泛型、枚举、注释
书中从Class类、cast、静态分析、动态分析、动态代理、Mock等各方面讲解类的RTTI解析,使用Generic实现对Java的扩展。JDK 5.0通过名为注释(Annotation)的新功能,将一个更通用的元数据工具合併到核心Java语言中。对于开发者来说,不仅可以使用JDK内置的注释,还可以使用第三方提供的强大注释功能,比如单元测试、EJB、Hibernate等,还可以自定义注释。
我的建议
由于AWT和Swing目前在实际套用中比例不高,并且擅长界面编程的中文图书比比皆是,因此就删除了图形化编程GUI一章。另外,本书开头的两章,即“Introduction to Objects”和“Everything Is an Object”没有收入本书。
还请读者留意以下两点:
(1)由于本评注版经重新编排,章节顺序与原着不尽相同,加之部分章节有所节略,因此书中涉及引用章节之处与图书现状略有出入。由此给读者带来的不便,还请谅解。
(2)各章练习序号后的小括弧中的文字,代表本练习的难度等级(用1~10表示)。
最后,在您阅读本书时,我有两点建议:
对经典的分析、代码及时做批注,多做对比和总结。
上机编写运行书中的经典实例,尝试不同的运行结果,分析代码的用意。
对书中的实例举一反三、反覆推敲,分析更多的实际套用场景。
只有用心去读、去体会、去实践,才能够真正理解Java编程中的思想。
本评注版由刘中兵、陈景春、周同、刘中敏、陈万珍、刘剑、李瑞霞、李建海、李金刚、刘中丽执笔,撰写相关中文评注。行文若有不妥之处,敬请广大读者提出宝贵意见和建议。
刘中兵
2011年4月20日于北京
目 录
第1部分 基本语法
Operators(新增批注30条) 1
Simpler print statements 1
Using Java operators 2
Precedence 2
Assignment 3
Mathematical operators 4
Unary minus and plus operators 6
Auto increment and decrement 6
Relational operators 7
Testing object equivalence 7
Logical operators 9
Literals 10
Exponential notation 11
Bitwise operators 12
Shift operators 13
Ternary if-else operator 16
String operator + and += 17
Common pitfalls when using
operators 18
Casting operators 18
Truncation and rounding 19
Promotion 20
Java has no “sizeof ” 20
Summary 20
Controlling Execution
(新增批注21条) 21
true and false 21
if-else 21
Iteration 22
do-while 23
for 23
The comma operator 24
Foreach syntax 25
return 27
break and continue 27
The infamous “goto” 29
switch 32
Summary 34
第2部分 面向对象
Initialization & Cleanup
(新增批注55条) 35
Guaranteed initialization with
the constructor 35
Method overloading 37
Distinguishing overloaded
methods 39
Overloading with primitives 39
Overloading on return values 42
Default constructors 43
The this keyword 44
Calling constructors from
constructors 46
The meaning of static 47
Cleanup: finalization and
garbage collection 47
What is finalize() for? 48
You must perform cleanup 49
The termination condition 50
How a garbage collector works 51
Member initialization 54
Specifying initialization 55
Constructor initialization 56
Order of initialization 56
static data initialization 57
Explicit static initialization 59
Non-static instance initialization 61
Array initialization 62
Variable argument lists 65
Enumerated types 70
Summary 72
Access Control
(新增批注21条) 73
package: the library unit 74
Code organization 75
Creating unique package names 76
A custom tool library 79
Java access specifiers 80
Package access 80
public: interface access 81
private: you can’t touch that! 82
protected: inheritance access 83
Interface and implementation 85
Class access 86
Summary 87
Reusing Classes
(新增批注35条) 89
Composition syntax 89
Inheritance syntax 92
Initializing the base class 94
Delegation 96
Combining composition and
inheritance 97
Guaranteeing proper cleanup 99
Name hiding 101
Choosing composition vs.
inheritance 103
protected 104
Upcasting 105
Why “upcasting”? 106
Composition vs. inheritance
revisited 106
The final keyword 107
final data 107
final methods 110
final classes 112
final caution 113
Initialization and class
loading 113
Initialization with inheritance 114
Summary 115
Interfaces
(新增批注16条) 117
Abstract classes and methods 117
Interfaces 120
“Multiple inheritance” in Java 123
Extending an interface with
inheritance 125
Name collisions when combining
interfaces 127
Fields in interfaces 127
Initializing fields in interfaces 128
Interfaces and factories 129
Summary 130
Inner Classes
(新增批注32条) 131
Creating inner classes 131
The link to the outer class 133
Using .this and .new 134
Inner classes and upcasting 135
Anonymous inner classes 137
Factory Method revisited 140
Nested classes 142
Classes inside interfaces 143
Reaching outward from a
multiply nested class 145
Why inner classes? 145
Closures & callbacks 148
Inheriting from inner classes 150
Can inner classes be
overridden? 150
Local inner classes 152
Inner-class identifiers 153
Summary 154
Error Handling with Excep- tions(新增批注52条) 155
Basic exceptions 155
Exception arguments 156
Catching an exception 157
The try block 157
Exception handlers . 157
Creating your own
exceptions 159
Exceptions and logging 161
The exception specification 164
Catching any exception 164
The stack trace 166
Rethrowing an exception 167
Exception chaining 169
Standard Java exceptions 172
Special case: RuntimeException 172
Performing cleanup with
finally 174
What’s finally for? 175
Using finally during return 177
Pitfall: the lost exception 178
Exception restrictions 180
Constructors 182
Exception matching 187
Alternative approaches 188
Passing exceptions to the console 189
Summary 189
第3部分 数据存储
Strings(新增批注53条) 191
Immutable Strings 191
Overloading ‘+’ vs.
StringBuilder 192
Unintended recursion 195
Operations on Strings 196
Formatting output 199
printf() 199
System.out.format() 199
The Formatter class 200
Format specifiers 200
Formatter conversions 202
String.format() 204
Regular expressions 205
Basics 206
Creating regular expressions 208
Quantifiers 210
Pattern and Matcher 211
split() 218
Replace operations 218
reset() 220
Regular expressions and Java I/O 221
Scanning input 222
Scanner delimiters 224
Scanning with regular
expressions 225
StringTokenizer 225
Summary 226
Arrays(新增批注36条) 227
Why arrays are special 227
Arrays are first-class objects 228
Returning an array 231
Multidimensional arrays 232
Arrays and generics 235
Creating test data 237
Arrays.fill() 238
Data Generators 239
Arrays utilities 243
Copying an array 243
Comparing arrays 244
Array element comparisons 245
Sorting an array 248
Searching a sorted array 249
Summary 251
Holding Your Objects
(新增批注35条) 253
Generics and type-safe
containers 254
Basic concepts 256
Adding groups of elements 258
Printing containers 259
List 261
Iterator 263
ListIterator 266
LinkedList 267
Stack 268
Set 270
Map 273
Queue 276
PriorityQueue 277
Collection vs. Iterator 279
Foreach and iterators 281
The Adapter Method idiom 283
Summary 286
Containers in Depth
(新增批注102条) 289
Full container taxonomy 289
Filling containers 290
A Generator solution 291
Map generators 292
Collection functionality 294
Optional operations 297
Unsupported operations 298
List functionality 300
Sets and storage order 302
SortedSet 306
Queues 307
Priority queues 308
Deques 309
Understanding Maps 310
Performance 311
SortedMap 314
LinkedHashMap 315
Hashing and hash codes 316
Understanding hashCode() 319
Hashing for speed 321
Overriding hashCode() 324
Choosing an implementation 329
A performance test framework 330
Choosing between Lists 333
Microbenchmarking dangers 338
Choosing between Sets 339
Choosing between Maps 341
Utilities 344
Sorting and searching Lists 347
Making a Collection or Map
unmodifiable 349
Synchronizing a Collection or
Map 350
Holding references 351
The WeakHashMap 353
Java 1.0/1.1 containers 355
Vector & Enumeration 355
Hashtable 356
Stack 356
BitSet 357
Summary 359
第4部分 核心功能
I/O(新增批注89条) 361
The File class 361
A directory lister 361
Directory utilities 364
Checking for and creating
directories 369
Input and output 370
Types of InputStream 371
Types of OutputStream 372
Adding attributes and useful
interfaces 373
Reading from an InputStream
with FilterInputStream 374
Writing to an OutputStream
with FilterOutputStream 375
Readers & Writers 376
Sources and sinks of data 377
Modifying stream behavior 377
Unchanged classes 378
Off by itself:
RandomAccessFile 379
Typical uses of I/O streams 379
Buffered input file 379
Input from memory 380
Formatted memory input 381
Basic file output 382
Storing and recovering data 383
Reading and writing
random-access files 385
Piped streams 386
File reading &
writing utilities 386
Reading binary files 389
Standard I/O 389
Reading from standard input 389
Changing System.out to a
PrintWriter 390
Redirecting standard I/O 391
Process control 391
New I/O 393
Converting data 396
Fetching primitives 398
View buffers 399
Data manipulation with buffers 403
Buffer details 404
Memory-mapped files 406
File locking 409
Compression 411
Simple compression with GZIP 412
Multifile storage with Zip 413
Java ARchives (JARs) 415
Object serialization 416
Finding the class 419
Controlling serialization 420
Using persistence 427
XML 432
Summary 434
Concurrency
(新增批注117条) 435
Basic threading 435
Defining tasks 435
The Thread class 436
Using Executors 438
Producing return values from
tasks 440
Sleeping 442
Priority 443
Yielding 444
Daemon threads 445
Coding variations 446
Joining a thread 450
Catching exceptions 451
Sharing resources 454
Resolving shared resource
contention 454
Atomicity and volatility 457
Atomic classes 460
Critical sections 462
Synchronizing on other objects 462
Thread local storage 463
Terminating tasks 464
The ornamental garden 465
Terminating when blocked 467
Interruption 469
Cooperation between tasks 475
wait() and notifyAll() 475
notify() vs. notifyAll() 479
Producers and consumers 482
Producer-consumers and queues 486
Using pipes for I/O between tasks 491
Deadlock 492
New library components 497
CountDownLatch 497
CyclicBarrier 499
DelayQueue 501
PriorityBlockingQueue 503
The greenhouse controller with
ScheduledExecutor 505
Semaphore 508
Exchanger 511
Simulation 513
Bank teller simulation 513
The restaurant simulation 517
Distributing work 521
Performance tuning 526
Comparing mutex technologies 526
Lock-free containers 532
ReadWriteLocks 533
Active objects 535
Summary 537
第5部分 高级特性
Type Information
(新增批注59条) 539
The need for RTTI 539
The Class object 541
Class literals 545
Generic class references 547
New cast syntax 549
Checking before a cast 550
Using class literals 555
A dynamic instanceof 557
Counting recursively 558
Registered factories 559
instanceof vs. Class
equivalence 562
Reflection: runtime class
information 563
A class method extractor 564
Dynamic proxies 566
Null Objects 570
Mock Objects & Stubs 575
Interfaces and type
information 576
Summary 580
Generics
(新增批注126条) 583
Comparison with C++ 584
Simple generics 584
A tuple library 586
A stack class 588
RandomList 589
Generic interfaces 590
Generic methods 593
Leveraging type argument
inference 594
Varargs and generic methods 596
A generic method to use with
Generators 596
A general-purpose Generator 597
Simplifying tuple use 598
A Set utility 600
Anonymous inner classes 603
Building complex models 604
The mystery of erasure 606
The C++ approach 607
Migration compatibility 609
The problem with erasure 611
The action at the boundaries 612
Compensating for erasure 615
Creating instances of types 616
Arrays of generics 618
Bounds 622
Wildcards 625
How smart is the compiler? 628
Contravariance 629
Unbounded wildcards 632
Capture conversion 636
Issues 637
No primitives as type parameters 637
Implementing parameterized
interfaces 639
Casting and warnings 640
Overloading 641
Base class hijacks an interface 642
Self-bounded types 642
Curiously-recurring generics 643
Self-bounding 644
Argument covariance 646
Dynamic type safety 649
Exceptions 650
Mixins 651
Mixins in C++ 651
Mixing with interfaces 653
Using the Decorator pattern 654
Mixins with dynamic proxies 655
Latent typing 657
Compensating for the lack of
latent typing 660
Reflection 661
Applying a method to a sequence 662
When you don’t happen
to have the right interface 664
Simulating latent typing
with adapters 665
Using function objects as
strategies 668
Summary: Is casting really
so bad? 672
Enumerated Types
(新增批注55条) 675
Basic enum features 675
Using static imports with enums 676
Adding methods to an enum 677
Overriding enum methods 678
enums in switch statements 678
The mystery of values() 679
Implements, not inherits 681
Random selection 682
Using interfaces for
organization 683
Using EnumSet instead of
flags 686
Using EnumMap 688
Constant-specific methods 689
Chain of Responsibility with
enums 692
State machines with enums 695
Multiple dispatching 700
Dispatching with enums 702
Using constant-specific methods 704
Dispatching with EnumMaps 705
Using a 2-D array 706
Summary 707
Annotations
(新增批注51条) 709
Basic syntax 710
Defining annotations 710
Meta-annotations 712
Writing annotation processors 712
Annotation elements 713
Default value constraints 713
Generating external files 714
Annotations don’t
support inheritance 717
Implementing the processor 717
Using apt to process
annotations 719
Using the Visitor pattern with
apt 723
Annotation-based unit testing 726
Using @Unit with generics 733
No “suites” necessary 735
Implementing @Unit 735
Removing test code 741
Sum