100% found this document useful (1 vote)
12 views

Download (eBook PDF) Java How To Program (Early Objects) 10th ebook All Chapters PDF

The document provides links to various eBooks available for download on ebookluna.com, including titles on Java and C++ programming. It highlights the availability of different editions and formats such as PDF, ePub, and MOBI for a better reading experience. Additionally, it mentions the collaboration with educators for global editions tailored for students outside North America.

Uploaded by

wruckenter7v
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
12 views

Download (eBook PDF) Java How To Program (Early Objects) 10th ebook All Chapters PDF

The document provides links to various eBooks available for download on ebookluna.com, including titles on Java and C++ programming. It highlights the availability of different editions and formats such as PDF, ePub, and MOBI for a better reading experience. Additionally, it mentions the collaboration with educators for global editions tailored for students outside North America.

Uploaded by

wruckenter7v
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Get the full ebook with Bonus Features for a Better Reading Experience on ebookluna.

com

(eBook PDF) Java How To Program (Early Objects)


10th

https://ebookluna.com/product/ebook-pdf-java-how-to-program-
early-objects-10th/

OR CLICK HERE

DOWLOAD NOW

Download more ebook instantly today at https://ebookluna.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

(eBook PDF) Java How to Program, Late Objects Global


Edition 11th Edition

https://ebookluna.com/product/ebook-pdf-java-how-to-program-late-
objects-global-edition-11th-edition/

ebookluna.com

(eBook PDF) Java How to Program, Early Objects 11th


Edition by Paul J. Deitel

https://ebookluna.com/product/ebook-pdf-java-how-to-program-early-
objects-11th-edition-by-paul-j-deitel/

ebookluna.com

C++ How to Program Early Objects Version 9th Edition


(eBook PDF)

https://ebookluna.com/product/c-how-to-program-early-objects-
version-9th-edition-ebook-pdf/

ebookluna.com

C++ How to Program: An Objects-Natural Approach, 11e 11th


Edition Paul Deitel - eBook PDF

https://ebookluna.com/download/c-how-to-program-an-objects-natural-
approach-11e-ebook-pdf/

ebookluna.com
(eBook PDF) Translational Medicine in CNS Drug
Development, Volume 29

https://ebookluna.com/product/ebook-pdf-translational-medicine-in-cns-
drug-development-volume-29/

ebookluna.com

Progress in Heterocyclic Chemistry Volume 29 1st Edition -


eBook PDF

https://ebookluna.com/download/progress-in-heterocyclic-chemistry-
ebook-pdf/

ebookluna.com

(eBook PDF) C++ How to Program 10th Edition by Paul J.


Deitel

https://ebookluna.com/product/ebook-pdf-c-how-to-program-10th-edition-
by-paul-j-deitel/

ebookluna.com

(eBook PDF) Big Java: Early Objects 5th Edition

https://ebookluna.com/product/ebook-pdf-big-java-early-objects-5th-
edition/

ebookluna.com

(eBook PDF) Big Java: Early Objects, 7th Edition

https://ebookluna.com/product/ebook-pdf-big-java-early-objects-7th-
edition/

ebookluna.com
Global Global
edition edition

edition
GlobalJava™ How to Program
For these Global Editions, the editorial team at Pearson has
collaborated with educators across the world to address a
wide range of subjects and requirements, equipping students

Early Objects
with the best possible learning tools. This Global Edition
preserves the cutting-edge approach and pedagogy of the
original, but also features alterations, customization and
adaptation from the North American version.

edition
TENTH
Java™ How to Program
Deitel • Deitel
This is a special edition of an established
title widely used by colleges and universities
throughout the world. Pearson published this
Early Objects
exclusive edition for the benefit of students
outside the United States and Canada. If you TENTH edition
purchased this book within the United States
or Canada you should be aware that it has
been imported without the approval of the
Publisher or Author.
Paul Deitel • Harvey Deitel
Pearson Global Edition
A01_DEIT7806_SE_10_TP.fm Page 6 Monday, July 7, 2014 12:37 PM

Trademarks
DEITEL, the double-thumbs-up bug and DIVE INTO are registered trademarks of Deitel and Associates,
Inc.
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks
of their respective owners.
Microsoft and/or its respective suppliers make no representations about the suitability of the information
contained in the documents and related graphics published as part of the services for any purpose. All
such documents and related graphics are provided “as is” without warranty of any kind. Microsoft and/
or its respective suppliers hereby disclaim all warranties and conditions with regard to this information,
including all warranties and conditions of merchantability, whether express, implied or statutory, fitness
for a particular purpose, title and non-infringement. In no event shall Microsoft and/or its respective sup-
pliers be liable for any special, indirect or consequential damages or any damages whatsoever resulting
from loss of use, data or profits, whether in an action of contract, negligence or other tortious action,
arising out of or in connection with the use or performance of information available from the services.
The documents and related graphics contained herein could include technical inaccuracies or typograph-
ical errors. Changes are periodically added to the information herein. Microsoft and/or its respective sup-
pliers may make improvements and/or changes in the product(s) and/or the program(s) described herein
at any time. Partial screen shots may be viewed in full within the software version specified.
Microsoft® and Windows® are registered trademarks of the Microsoft Corporation in the U.S.A. and
other countries. Screen shots and icons reprinted with permission from the Microsoft Corporation. This
book is not sponsored or endorsed by or affiliated with the Microsoft Corporation.UNIX is a registered
trademark of The Open Group.
Apache is a trademark of The Apache Software Foundation.
CSS and XML are registered trademarks of the World Wide Web Consortium.
Firefox is a registered trademark of the Mozilla Foundation.
Google is a trademark of Google, Inc.
Mac and OS X are trademarks of Apple Inc., registered in the U.S. and other countries.
Linux is a registered trademark of Linus Torvalds. All trademarks are property of their respective owners.
Throughout this book, trademarks are used. Rather than put a trademark symbol in every occurrence of
a trademarked name, we state that we are using the names in an editorial fashion only and to the benefit
of the trademark owner, with no intention of infringement of the trademark.
A02_DEIT7806_SE_10_TOC.fm Page 7 Monday, July 7, 2014 11:59 AM

Contents
Chapters 26–34 and Appendices F–N are PDF documents posted online at the book’s
Companion Website (located at www.pearsonglobaleditions.com/deitel). See the in-
side front cover for information on accessing the Companion Website.

Foreword 23
Preface 25
Before You Begin 39
1 Introduction to Computers, the Internet and Java 43
1.1 Introduction 44
1.2 Hardware and Software 46
1.2.1 Moore’s Law 46
1.2.2 Computer Organization 47
1.3 Data Hierarchy 48
1.4 Machine Languages, Assembly Languages and High-Level Languages 51
1.5 Introduction to Object Technology 52
1.5.1 The Automobile as an Object 52
1.5.2 Methods and Classes 53
1.5.3 Instantiation 53
1.5.4 Reuse 53
1.5.5 Messages and Method Calls 53
1.5.6 Attributes and Instance Variables 53
1.5.7 Encapsulation and Information Hiding 54
1.5.8 Inheritance 54
1.5.9 Interfaces 54
1.5.10 Object-Oriented Analysis and Design (OOAD) 54
1.5.11 The UML (Unified Modeling Language) 55
1.6 Operating Systems 55
1.6.1 Windows—A Proprietary Operating System 55
1.6.2 Linux—An Open-Source Operating System 56
1.6.3 Android 56
1.7 Programming Languages 57
1.8 Java 59
1.9 A Typical Java Development Environment 59
1.10 Test-Driving a Java Application 63
A02_DEIT7806_SE_10_TOC.fm Page 8 Monday, July 7, 2014 11:59 AM

8 Contents

1.11 Internet and World Wide Web 67


1.11.1 The Internet: A Network of Networks 68
1.11.2 The World Wide Web: Making the Internet User-Friendly 68
1.11.3 Web Services and Mashups 68
1.11.4 Ajax 69
1.11.5 The Internet of Things 69
1.12 Software Technologies 70
1.13 Keeping Up-to-Date with Information Technologies 72

2 Introduction to Java Applications;


Input/Output and Operators 76
2.1 Introduction 77
2.2 Your First Program in Java: Printing a Line of Text 77
2.3 Modifying Your First Java Program 83
2.4 Displaying Text with printf 85
2.5 Another Application: Adding Integers 87
2.5.1 import Declarations 87
2.5.2 Declaring Class Addition 88
2.5.3 Declaring and Creating a Scanner to Obtain User Input from
the Keyboard 88
2.5.4 Declaring Variables to Store Integers 89
2.5.5 Prompting the User for Input 90
2.5.6 Obtaining an int as Input from the User 90
2.5.7 Prompting for and Inputting a Second int 91
2.5.8 Using Variables in a Calculation 91
2.5.9 Displaying the Result of the Calculation 91
2.5.10 Java API Documentation 91
2.6 Memory Concepts 92
2.7 Arithmetic 93
2.8 Decision Making: Equality and Relational Operators 96
2.9 Wrap-Up 100

3 Introduction to Classes, Objects, Methods


and Strings 111
3.1 Introduction 112
3.2 Instance Variables, set Methods and get Methods 113
3.2.1 Account Class with an Instance Variable, a set Method and
a get Method 113
3.2.2 AccountTest Class That Creates and Uses an Object of
Class Account 116
3.2.3 Compiling and Executing an App with Multiple Classes 119
3.2.4 Account UML Class Diagram with an Instance Variable and
set and get Methods 119
3.2.5 Additional Notes on Class AccountTest 120
A02_DEIT7806_SE_10_TOC.fm Page 9 Monday, July 7, 2014 11:59 AM

Contents 9

3.2.6 Software Engineering with private Instance Variables and


public set and get Methods 121
3.3 Primitive Types vs. Reference Types 122
3.4 Account Class: Initializing Objects with Constructors 123
3.4.1 Declaring an Account Constructor for Custom Object Initialization 123
3.4.2 Class AccountTest: Initializing Account Objects When
They’re Created 124
3.5 Account Class with a Balance; Floating-Point Numbers 126
3.5.1 Account Class with a balance Instance Variable of Type double 127
3.5.2 AccountTest Class to Use Class Account 128
3.6 (Optional) GUI and Graphics Case Study: Using Dialog Boxes 132
3.7 Wrap-Up 135

4 Control Statements: Part 1; Assignment,


++ and -- Operators 143
4.1 Introduction 144
4.2 Algorithms 144
4.3 Pseudocode 145
4.4 Control Structures 145
4.5 if Single-Selection Statement 147
4.6 if…else Double-Selection Statement 148
4.7 Student Class: Nested if…else Statements 153
4.8 while Repetition Statement 155
4.9 Formulating Algorithms: Counter-Controlled Repetition 157
4.10 Formulating Algorithms: Sentinel-Controlled Repetition 161
4.11 Formulating Algorithms: Nested Control Statements 168
4.12 Compound Assignment Operators 173
4.13 Increment and Decrement Operators 173
4.14 Primitive Types 176
4.15 (Optional) GUI and Graphics Case Study: Creating Simple Drawings 177
4.16 Wrap-Up 181

5 Control Statements: Part 2; Logical Operators 194


5.1 Introduction 195
5.2 Essentials of Counter-Controlled Repetition 195
5.3 for Repetition Statement 197
5.4 Examples Using the for Statement 201
5.5 do…while Repetition Statement 205
5.6 switch Multiple-Selection Statement 207
5.7 Class AutoPolicy Case Study: Strings in switch Statements 213
5.8 break and continue Statements 216
5.9 Logical Operators 218
5.10 Structured Programming Summary 224
5.11 (Optional) GUI and Graphics Case Study: Drawing Rectangles and Ovals 229
5.12 Wrap-Up 232
A02_DEIT7806_SE_10_TOC.fm Page 10 Monday, July 7, 2014 11:59 AM

10 Contents

6 Methods: A Deeper Look 242


6.1 Introduction 243
6.2 Program Modules in Java 243
6.3 static Methods, static Fields and Class Math 245
6.4 Declaring Methods with Multiple Parameters 247
6.5 Notes on Declaring and Using Methods 250
6.6 Method-Call Stack and Stack Frames 251
6.7 Argument Promotion and Casting 252
6.8 Java API Packages 253
6.9 Case Study: Secure Random-Number Generation 255
6.10 Case Study: A Game of Chance; Introducing enum Types 260
6.11 Scope of Declarations 264
6.12 Method Overloading 267
6.13 (Optional) GUI and Graphics Case Study: Colors and Filled Shapes 269
6.14 Wrap-Up 272

7 Arrays and ArrayLists 285


7.1 Introduction 286
7.2 Arrays 287
7.3 Declaring and Creating Arrays 288
7.4 Examples Using Arrays 289
7.4.1 Creating and Initializing an Array 289
7.4.2 Using an Array Initializer 290
7.4.3 Calculating the Values to Store in an Array 291
7.4.4 Summing the Elements of an Array 293
7.4.5 Using Bar Charts to Display Array Data Graphically 293
7.4.6 Using the Elements of an Array as Counters 295
7.4.7 Using Arrays to Analyze Survey Results 296
7.5 Exception Handling: Processing the Incorrect Response 298
7.5.1 The try Statement 298
7.5.2 Executing the catch Block 298
7.5.3 toString Method of the Exception Parameter 299
7.6 Case Study: Card Shuffling and Dealing Simulation 299
7.7 Enhanced for Statement 304
7.8 Passing Arrays to Methods 305
7.9 Pass-By-Value vs. Pass-By-Reference 307
7.10 Case Study: Class GradeBook Using an Array to Store Grades 308
7.11 Multidimensional Arrays 314
7.12 Case Study: Class GradeBook Using a Two-Dimensional Array 317
7.13 Variable-Length Argument Lists 323
7.14 Using Command-Line Arguments 325
7.15 Class Arrays 327
7.16 Introduction to Collections and Class ArrayList 329
7.17 (Optional) GUI and Graphics Case Study: Drawing Arcs 333
7.18 Wrap-Up 336
A02_DEIT7806_SE_10_TOC.fm Page 11 Monday, July 7, 2014 11:59 AM

Contents 11

8 Classes and Objects: A Deeper Look 357


8.1 Introduction 358
8.2 Time Class Case Study 358
8.3 Controlling Access to Members 363
8.4 Referring to the Current Object’s Members with the this Reference 364
8.5 Time Class Case Study: Overloaded Constructors 366
8.6 Default and No-Argument Constructors 372
8.7 Notes on Set and Get Methods 372
8.8 Composition 374
8.9 enum Types 377
8.10 Garbage Collection 379
8.11 static Class Members 380
8.12 static Import 384
8.13 final Instance Variables 385
8.14 Package Access 386
8.15 Using BigDecimal for Precise Monetary Calculations 387
8.16 (Optional) GUI and Graphics Case Study: Using Objects with Graphics 390
8.17 Wrap-Up 394

9 Object-Oriented Programming: Inheritance 402


9.1 Introduction 403
9.2 Superclasses and Subclasses 404
9.3 protected Members 406
9.4 Relationship Between Superclasses and Subclasses 407
9.4.1 Creating and Using a CommissionEmployee Class 407
9.4.2 Creating and Using a BasePlusCommissionEmployee Class 413
9.4.3 Creating a CommissionEmployee–BasePlusCommissionEmployee
Inheritance Hierarchy 418
9.4.4 CommissionEmployee–BasePlusCommissionEmployee
Inheritance Hierarchy Using protected Instance Variables 421
9.4.5 CommissionEmployee–BasePlusCommissionEmployee
Inheritance Hierarchy Using private Instance Variables 424
9.5 Constructors in Subclasses 429
9.6 Class Object 429
9.7 (Optional) GUI and Graphics Case Study: Displaying Text and
Images Using Labels 430
9.8 Wrap-Up 433

10 Object-Oriented Programming:
Polymorphism and Interfaces 437
10.1 Introduction 438
10.2 Polymorphism Examples 440
10.3 Demonstrating Polymorphic Behavior 441
10.4 Abstract Classes and Methods 443
A02_DEIT7806_SE_10_TOC.fm Page 12 Monday, July 7, 2014 11:59 AM

12 Contents

10.5 Case Study: Payroll System Using Polymorphism 446


10.5.1 Abstract Superclass Employee 447
10.5.2 Concrete Subclass SalariedEmployee 449
10.5.3 Concrete Subclass HourlyEmployee 451
10.5.4 Concrete Subclass CommissionEmployee 453
10.5.5 Indirect Concrete Subclass BasePlusCommissionEmployee 455
10.5.6 Polymorphic Processing, Operator instanceof and Downcasting 456
10.6 Allowed Assignments Between Superclass and Subclass Variables 461
10.7 final Methods and Classes 461
10.8 A Deeper Explanation of Issues with Calling Methods from Constructors 462
10.9 Creating and Using Interfaces 463
10.9.1 Developing a Payable Hierarchy 464
10.9.2 Interface Payable 465
10.9.3 Class Invoice 466
10.9.4 Modifying Class Employee to Implement Interface Payable 468
10.9.5 Modifying Class SalariedEmployee for Use in the Payable
Hierarchy 470
10.9.6 Using Interface Payable to Process Invoices and Employees
Polymorphically 472
10.9.7 Some Common Interfaces of the Java API 473
10.10 Java SE 8 Interface Enhancements 474
10.10.1 default Interface Methods 474
10.10.2 static Interface Methods 475
10.10.3 Functional Interfaces 475
10.11 (Optional) GUI and Graphics Case Study: Drawing with Polymorphism 475
10.12 Wrap-Up 478

11 Exception Handling: A Deeper Look 483


11.1 Introduction 484
11.2 Example: Divide by Zero without Exception Handling 485
11.3 Example: Handling ArithmeticExceptions and InputMismatchExceptions 487
11.4 When to Use Exception Handling 493
11.5 Java Exception Hierarchy 493
11.6 finally Block 496
11.7 Stack Unwinding and Obtaining Information from an Exception Object 501
11.8 Chained Exceptions 503
11.9 Declaring New Exception Types 506
11.10 Preconditions and Postconditions 507
11.11 Assertions 507
11.12 try-with-Resources: Automatic Resource Deallocation 509
11.13 Wrap-Up 509

12 GUI Components: Part 1 515


12.1 Introduction 516
A02_DEIT7806_SE_10_TOC.fm Page 13 Monday, July 7, 2014 11:59 AM

Contents 13

12.2 Java’s Nimbus Look-and-Feel 517


12.3 Simple GUI-Based Input/Output with JOptionPane 518
12.4 Overview of Swing Components 521
12.5 Displaying Text and Images in a Window 523
12.6 Text Fields and an Introduction to Event Handling with Nested Classes 527
12.7 Common GUI Event Types and Listener Interfaces 533
12.8 How Event Handling Works 535
12.9 JButton 537
12.10 Buttons That Maintain State 540
12.10.1 JCheckBox 541
12.10.2 JRadioButton 543
12.11 JComboBox; Using an Anonymous Inner Class for Event Handling 546
12.12 JList 550
12.13 Multiple-Selection Lists 553
12.14 Mouse Event Handling 555
12.15 Adapter Classes 560
12.16 JPanel Subclass for Drawing with the Mouse 564
12.17 Key Event Handling 567
12.18 Introduction to Layout Managers 570
12.18.1 FlowLayout 572
12.18.2 BorderLayout 574
12.18.3 GridLayout 578
12.19 Using Panels to Manage More Complex Layouts 580
12.20 JTextArea 581
12.21 Wrap-Up 584

13 Graphics and Java 2D 597


13.1 Introduction 598
13.2 Graphics Contexts and Graphics Objects 600
13.3 Color Control 601
13.4 Manipulating Fonts 608
13.5 Drawing Lines, Rectangles and Ovals 613
13.6 Drawing Arcs 617
13.7 Drawing Polygons and Polylines 620
13.8 Java 2D API 623
13.9 Wrap-Up 630

14 Strings, Characters and Regular Expressions 638


14.1 Introduction 639
14.2 Fundamentals of Characters and Strings 639
14.3 Class String 640
14.3.1 String Constructors 640
14.3.2 String Methods length, charAt and getChars 641
14.3.3 Comparing Strings 642
A02_DEIT7806_SE_10_TOC.fm Page 14 Monday, July 7, 2014 11:59 AM

14 Contents

14.3.4 Locating Characters and Substrings in Strings 647


14.3.5 Extracting Substrings from Strings 649
14.3.6 Concatenating Strings 650
14.3.7 Miscellaneous String Methods 650
14.3.8 String Method valueOf 652
14.4 Class StringBuilder 653
14.4.1 StringBuilder Constructors 654
14.4.2 StringBuilder Methods length, capacity, setLength
and ensureCapacity 654
14.4.3 StringBuilder Methods charAt, setCharAt, getChars
and reverse 656
14.4.4 StringBuilder append Methods 657
14.4.5 StringBuilder Insertion and Deletion Methods 659
14.5 Class Character 660
14.6 Tokenizing Strings 665
14.7 Regular Expressions, Class Pattern and Class Matcher 666
14.8 Wrap-Up 675

15 Files, Streams and Object Serialization 686


15.1 Introduction 687
15.2 Files and Streams 687
15.3 Using NIO Classes and Interfaces to Get File and Directory Information 689
15.4 Sequential-Access Text Files 693
15.4.1 Creating a Sequential-Access Text File 693
15.4.2 Reading Data from a Sequential-Access Text File 697
15.4.3 Case Study: A Credit-Inquiry Program 699
15.4.4 Updating Sequential-Access Files 703
15.5 Object Serialization 704
15.5.1 Creating a Sequential-Access File Using Object Serialization 705
15.5.2 Reading and Deserializing Data from a Sequential-Access File 710
15.6 Opening Files with JFileChooser 712
15.7 (Optional) Additional java.io Classes 715
15.7.1 Interfaces and Classes for Byte-Based Input and Output 715
15.7.2 Interfaces and Classes for Character-Based Input and Output 717
15.8 Wrap-Up 718

16 Generic Collections 726


16.1 Introduction 727
16.2 Collections Overview 727
16.3 Type-Wrapper Classes 729
16.4 Autoboxing and Auto-Unboxing 729
16.5 Interface Collection and Class Collections 729
16.6 Lists 730
16.6.1 ArrayList and Iterator 731
16.6.2 LinkedList 733
A02_DEIT7806_SE_10_TOC.fm Page 15 Monday, July 7, 2014 11:59 AM

Contents 15

16.7 Collections Methods 738


16.7.1 Method sort 739
16.7.2 Method shuffle 742
16.7.3 Methods reverse, fill, copy, max and min 744
16.7.4 Method binarySearch 746
16.7.5 Methods addAll, frequency and disjoint 748
16.8 Stack Class of Package java.util 750
16.9 Class PriorityQueue and Interface Queue 752
16.10 Sets 753
16.11 Maps 756
16.12 Properties Class 760
16.13 Synchronized Collections 763
16.14 Unmodifiable Collections 763
16.15 Abstract Implementations 764
16.16 Wrap-Up 764

17 Java SE 8 Lambdas and Streams 771


17.1 Introduction 772
17.2 Functional Programming Technologies Overview 773
17.2.1 Functional Interfaces 774
17.2.2 Lambda Expressions 775
17.2.3 Streams 776
17.3 IntStream Operations 778
17.3.1 Creating an IntStream and Displaying Its Values with the
forEach Terminal Operation 780
17.3.2 Terminal Operations count, min, max, sum and average 781
17.3.3 Terminal Operation reduce 781
17.3.4 Intermediate Operations: Filtering and Sorting IntStream Values 783
17.3.5 Intermediate Operation: Mapping 784
17.3.6 Creating Streams of ints with IntStream Methods range and
rangeClosed 785
17.4 Stream<Integer> Manipulations 785
17.4.1 Creating a Stream<Integer> 786
17.4.2 Sorting a Stream and Collecting the Results 787
17.4.3 Filtering a Stream and Storing the Results for Later Use 787
17.4.4 Filtering and Sorting a Stream and Collecting the Results 787
17.4.5 Sorting Previously Collected Results 787
17.5 Stream<String> Manipulations 788
17.5.1 Mapping Strings to Uppercase Using a Method Reference 789
17.5.2 Filtering Strings Then Sorting Them in Case-Insensitive
Ascending Order 790
17.5.3 Filtering Strings Then Sorting Them in Case-Insensitive
Descending Order 790
17.6 Stream<Employee> Manipulations 790
17.6.1 Creating and Displaying a List<Employee> 792
A02_DEIT7806_SE_10_TOC.fm Page 16 Monday, July 7, 2014 11:59 AM

16 Contents

17.6.2 Filtering Employees with Salaries in a Specified Range 793


17.6.3 Sorting Employees By Multiple Fields 794
17.6.4 Mapping Employees to Unique Last Name Strings 796
17.6.5 Grouping Employees By Department 797
17.6.6 Counting the Number of Employees in Each Department 798
17.6.7 Summing and Averaging Employee Salaries 798
17.7 Creating a Stream<String> from a File 800
17.8 Generating Streams of Random Values 803
17.9 Lambda Event Handlers 805
17.10 Additional Notes on Java SE 8 Interfaces 805
17.11 Java SE 8 and Functional Programming Resources 806
17.12 Wrap-Up 806

18 Recursion 818
18.1 Introduction 819
18.2 Recursion Concepts 820
18.3 Example Using Recursion: Factorials 821
18.4 Reimplementing Class FactorialCalculator Using Class BigInteger 823
18.5 Example Using Recursion: Fibonacci Series 825
18.6 Recursion and the Method-Call Stack 828
18.7 Recursion vs. Iteration 829
18.8 Towers of Hanoi 831
18.9 Fractals 833
18.9.1 Koch Curve Fractal 833
18.9.2 (Optional) Case Study: Lo Feather Fractal 834
18.10 Recursive Backtracking 843
18.11 Wrap-Up 844

19 Searching, Sorting and Big O 852


19.1 Introduction 853
19.2 Linear Search 854
19.3 Big O Notation 856
19.3.1 O(1) Algorithms 856
19.3.2 O(n) Algorithms 857
19.3.3 O(n2) Algorithms 857
19.3.4 Big O of the Linear Search 858
19.4 Binary Search 858
19.4.1 Binary Search Implementation 859
19.4.2 Efficiency of the Binary Search 862
19.5 Sorting Algorithms 862
19.6 Selection Sort 863
19.6.1 Selection Sort Implementation 863
19.6.2 Efficiency of the Selection Sort 866
19.7 Insertion Sort 866
A02_DEIT7806_SE_10_TOC.fm Page 17 Monday, July 7, 2014 11:59 AM

Contents 17

19.7.1 Insertion Sort Implementation 867


19.7.2 Efficiency of the Insertion Sort 869
19.8 Merge Sort 869
19.8.1 Merge Sort Implementation 870
19.8.2 Efficiency of the Merge Sort 874
19.9 Big O Summary for This Chapter’s Searching and Sorting Algorithms 875
19.10 Wrap-Up 876

20 Generic Classes and Methods 881


20.1 Introduction 882
20.2 Motivation for Generic Methods 882
20.3 Generic Methods: Implementation and Compile-Time Translation 884
20.4 Additional Compile-Time Translation Issues: Methods That Use a
Type Parameter as the Return Type 887
20.5 Overloading Generic Methods 890
20.6 Generic Classes 891
20.7 Raw Types 898
20.8 Wildcards in Methods That Accept Type Parameters 902
20.9 Wrap-Up 906

21 Custom Generic Data Structures 911


21.1 Introduction 912
21.2 Self-Referential Classes 913
21.3 Dynamic Memory Allocation 913
21.4 Linked Lists 914
21.4.1 Singly Linked Lists 914
21.4.2 Implementing a Generic List Class 915
21.4.3 Generic Classes ListNode and List 920
21.4.4 Class ListTest 920
21.4.5 List Method insertAtFront 920
21.4.6 List Method insertAtBack 921
21.4.7 List Method removeFromFront 922
21.4.8 List Method removeFromBack 923
21.4.9 List Method print 924
21.4.10 Creating Your Own Packages 924
21.5 Stacks 928
21.6 Queues 932
21.7 Trees 935
21.8 Wrap-Up 942

22 GUI Components: Part 2 953


22.1 Introduction 954
22.2 JSlider 954
A02_DEIT7806_SE_10_TOC.fm Page 18 Monday, July 7, 2014 11:59 AM

18 Contents

22.3 Understanding Windows in Java 958


22.4 Using Menus with Frames 959
22.5 JPopupMenu 967
22.6 Pluggable Look-and-Feel 970
22.7 JDesktopPane and JInternalFrame 975
22.8 JTabbedPane 978
22.9 BoxLayout Layout Manager 980
22.10 GridBagLayout Layout Manager 984
22.11 Wrap-Up 994

23 Concurrency 999
23.1 Introduction 1000
23.2 Thread States and Life Cycle 1002
23.2.1 New and Runnable States 1003
23.2.2 Waiting State 1003
23.2.3 Timed Waiting State 1003
23.2.4 Blocked State 1003
23.2.5 Terminated State 1003
23.2.6 Operating-System View of the Runnable State 1004
23.2.7 Thread Priorities and Thread Scheduling 1004
23.2.8 Indefinite Postponement and Deadlock 1005
23.3 Creating and Executing Threads with the Executor Framework 1005
23.4 Thread Synchronization 1009
23.4.1 Immutable Data 1010
23.4.2 Monitors 1010
23.4.3 Unsynchronized Mutable Data Sharing 1011
23.4.4 Synchronized Mutable Data Sharing—Making Operations Atomic 1016
23.5 Producer/Consumer Relationship without Synchronization 1018
23.6 Producer/Consumer Relationship: ArrayBlockingQueue 1026
23.7 (Advanced) Producer/Consumer Relationship with synchronized,
wait, notify and notifyAll 1029
23.8 (Advanced) Producer/Consumer Relationship: Bounded Buffers 1036
23.9 (Advanced) Producer/Consumer Relationship: The Lock and
Condition Interfaces 1044
23.10 Concurrent Collections 1051
23.11 Multithreading with GUI: SwingWorker 1053
23.11.1 Performing Computations in a Worker Thread:
Fibonacci Numbers 1054
23.11.2 Processing Intermediate Results: Sieve of Eratosthenes 1060
23.12 sort and parallelSort Timings with the Java SE 8 Date/Time API 1067
23.13 Java SE 8: Sequential vs. Parallel Streams 1069
23.14 (Advanced) Interfaces Callable and Future 1072
23.15 (Advanced) Fork/Join Framework 1076
23.16 Wrap-Up 1076
A02_DEIT7806_SE_10_TOC.fm Page 19 Monday, July 7, 2014 11:59 AM

Contents 19

24 Accessing Databases with JDBC 1087


24.1 Introduction 1088
24.2 Relational Databases 1089
24.3 A books Database 1090
24.4 SQL 1094
24.4.1 Basic SELECT Query 1094
24.4.2 WHERE Clause 1095
24.4.3 ORDER BY Clause 1097
24.4.4 Merging Data from Multiple Tables: INNER JOIN 1098
24.4.5 INSERT Statement 1100
24.4.6 UPDATE Statement 1101
24.4.7 DELETE Statement 1102
24.5 Setting up a Java DB Database 1102
24.5.1 Creating the Chapter’s Databases on Windows 1103
24.5.2 Creating the Chapter’s Databases on Mac OS X 1104
24.5.3 Creating the Chapter’s Databases on Linux 1105
24.6 Manipulating Databases with JDBC 1105
24.6.1 Connecting to and Querying a Database 1105
24.6.2 Querying the books Database 1109
24.7 RowSet Interface 1122
24.8 PreparedStatements 1124
24.9 Stored Procedures 1140
24.10 Transaction Processing 1140
24.11 Wrap-Up 1141

25 JavaFX GUI: Part 1 1149


25.1 Introduction 1150
25.2 JavaFX Scene Builder and the NetBeans IDE 1151
25.3 JavaFX App Window Structure 1152
25.4 Welcome App—Displaying Text and an Image 1153
25.4.1 Creating the App’s Project 1153
25.4.2 NetBeans Projects Window—Viewing the Project Contents 1155
25.4.3 Adding an Image to the Project 1156
25.4.4 Opening JavaFX Scene Builder from NetBeans 1156
25.4.5 Changing to a VBox Layout Container 1157
25.4.6 Configuring the VBox Layout Container 1158
25.4.7 Adding and Configuring a Label 1158
25.4.8 Adding and Configuring an ImageView 1158
25.4.9 Running the Welcome App 1159
25.5 Tip Calculator App—Introduction to Event Handling 1160
25.5.1 Test-Driving the Tip Calculator App 1161
25.5.2 Technologies Overview 1161
25.5.3 Building the App’s GUI 1164
25.5.4 TipCalculator Class 1168
25.5.5 TipCalculatorController Class 1170
Random documents with unrelated
content Scribd suggests to you:
in history were such fierce battles fought, such bodies of men
dispersed, such losses of life sustained, and such paltry results
accomplished. On more than one occasion a sovereign, the moral
effect of whose capture would have been almost equivalent to a
great victory, was suffered to escape from the very hands of the
enemy. In a few weeks a force which had been apparently destroyed
confronted the victor as defiantly as ever. The defenceless condition
of the Moslem states had been thoroughly established. Their
territory had been penetrated in every direction by squadrons of
Christian cavalry, whose numbers, when compared with the
inhabitants of the provinces they despoiled, were insignificant. The
invaders dispersed with ease large bodies of the effeminate
Andalusian horsemen. They encamped with impunity in the vicinity
of populous cities. But these expeditions accomplished but little
more than the destruction of a few harvests and the burning of a
few villages. The campaigns on both sides were ordinarily
distinguished by fraternal discord, military incapacity, and fatal
indecision.
The correctness of these observations may be established by
recurring to the consequences of the battle of Fraga. The rout of the
Christians and the death of their king would certainly seem to have
demanded a vigorous prosecution of hostilities by the victors before
the popular demoralization resulting from such a catastrophe
subsided. But nothing of the kind took place. The few survivors of
the defeat which had wrecked the hopes of a nation spread dismay
through the realms of the Christians. In Aragon, part of whose
territory had recently been ceded by a degenerate prince to his
hereditary enemies, and none of which was in sympathy with the
usurpation of their detested masters, the people expected, with
eager but fallacious hopes, the appearance of the deliverer. The
merchants lounged idly in their shops. The peasantry, with sullen
patience, submitted to the extortions of the Jewish farmers of the
revenue. Saragossa was still, in all but name and government, a
Moslem city. The muezzin still announced from her minarets the hour
of prayer. The imam still read the Koran from the pulpits of her
mosques. Her occupation by the Aragonese had only served to
intensify the hatred entertained by her citizens against those who
had profited by their betrayal. The noble recalled with mingled
sorrow and exultation the military fame and intellectual pursuits of
the royal House of Ibn-Hud; the husbandman viewed with
unconcealed resentment the encroachments of the Church and the
Crown upon his small but valuable inheritance. The valley of the
Ebro still possessed many fortresses defended by natural
impediments and Moslem valor. All these considerations invited the
intervention of the victors, but the Moorish commander, satisfied
with the barren laurels acquired at Fraga, neglected an opportunity
which might have restored to the Almoravide Sultan one of the most
important provinces of his empire. For several years the frontier was
wasted by implacable partisan warfare; the Moslems carried into
slavery the populations of entire communities; the Christians,
harassed by the enemy and encumbered with their prisoners,
frequently put these defenceless victims of their hostility to the
sword; in the heat of battle quarter was neither asked nor given,
and the struggle assumed more than ever the character of a war of
extermination. The country devastated by these incessant and
destructive inroads never recovered its prosperity. The once beautiful
regions of the Ebro and the Pisuerga now present to the eye the
sombre and monotonous aspect of a desert, and portions of the
valley of the Guadalquivir, which under Moorish rule were clothed
with extensive orchards and luxuriant harvests, have lapsed into
primeval desolation. The ruthlessness with which these wars were
prosecuted bears ample testimony to the savage inhumanity of that
age. Considerations of mercy seldom influenced the conduct of the
victor. Engagements contracted under circumstances of peculiar
solemnity were violated without provocation and without excuse. In
the perpetration of these enormities the Christians, encouraged and
absolved by their spiritual advisers, far surpassed their antagonists.
No attention was paid to the pitiful appeals of enemies stricken in
the heat of battle. The heads of rebellious princes were fixed on the
battlements of cities; their limbs, embalmed with campher, were
exhibited as trophies in the palace of the conqueror. When a place
was taken by storm, neither age, nor sex, nor infirmity were
regarded by the infuriated assailants. The discovery of hidden gold
by the application of torture was a favorite amusement of the
Christian soldiery. If the number of captives became inconveniently
large, the least valuable were butchered. The licentious passions of
the Castilians were exercised without restraint upon the weak and
the defenceless. Women were violated before the eyes of their
husbands and fathers. The mansions of Christian nobles rivalled in
their treasures of Moorish beauty the harems of the most voluptuous
Andalusian princes. In the alluring diversions of sensuality,
unsanctioned by law and prohibited by religion, the dignitaries of the
Church were as ever pre-eminently conspicuous; and their lovely
concubines, attired with a magnificence only to be procured by the
use of ecclesiastical wealth, appeared at court with their lords,
equally careless of unfavorable comment or of public scandal.
In Africa the movements of Abd-al-Mumen, who had been the
general of the Almohades and was now their sovereign, began to
excite the alarm of Ali. The successor of the Mahdi began his reign
with an expedition whose destructive course extended to the city of
Morocco. Tashfin, the ablest of the Almoravide captains, was recalled
from Spain; but, despite his reputation and the skilful disposition of
his forces, the battalions of Ali, dominated by a craven and
superstitious fear, instinctively recoiled from the presence of the
enemy. All the experience and resolution of the youthful prince, who
had redeemed the Moslem cause in the Peninsula, were insufficient
to counteract the evil influence emanating from religious fraud,
which, by the force of a distempered imagination, could transform a
bold and courageous people into a race of poltroons and slaves. His
continual reverses preyed upon the mind of Ali, and his moments
were distracted by the signs of the imminent and apparently
inevitable collapse of his power. The memory of his early grandeur
offered a distressing contrast to the misfortunes of his declining
years; and, overcome with mortification and sorrow, he passed from
life, bequeathing to his son Tashfin a disheartened army, an
exhausted treasury, and a royal inheritance of diminished jurisdiction
and doubtful value.
The ill-fortune of Tashfin followed him upon the throne. Defeated
by Abd-al-Mumen, he collected all his resources for a supreme and
final effort. Such of the Desert tribes as had held aloof from the
Mahdi were enlisted. Every available soldier in Africa was called to
arms. The garrisons of Andalusia were almost denuded of troops.
With the Moorish squadrons of Spain came also a body of four
thousand Mozarabes, who, accustomed to long service under
Moslem standards, had almost forgotten their ancestry, their
traditions, and their faith. These auxiliaries, amenable to discipline
and experienced in border warfare, were far more formidable than
their scanty numbers would denote.
On the plains of Tlemcen the two armies whose valor was to
decide the fate of an empire faced each other. The Almoravides far
outnumbered their foes, but the mystic spell of superstition more
than compensated for numerical superiority; the soldiers of Tashfin
were terrified by imaginary apparitions and supernatural voices, and
after a brief but sanguinary contest Abd-al-Mumen remained master
of the field. Tashfin was soon afterwards killed in the vicinity of Oran
by a fall from a precipice, and with his death vanished the last hope
of the Almoravide monarchy.
During the year 1145 a famous landmark of the Mediterranean, of
unknown antiquity, but most probably of Phœnician origin, was
destroyed. Near the city of Cadiz, and built in the waters of the bay,
had long stood a structure composed of a series of columns, rising
above each other to the height of one hundred and eighty feet and
surmounted by a colossal statue of bronze. The latter represented a
man with his right arm extended towards the Strait of Gibraltar and
grasping in his hand a key. The entire statue was heavily plated with
gold, and was a conspicuous object for a distance of many leagues.
Its origin was not less mysterious than the reason for its
preservation for nearly four centuries and a half after the Moslem
conquest. The well-known iconoclastic propensities of the followers
of Mohammed were indulged with every opportunity and against
every symbol of idolatrous worship. There was probably no souvenir
of Pagan antiquity in Africa or Spain so prominent and so well known
as the effigy which, for a period unrecorded even by tradition,
indicated to the mariner the gateway of the Mediterranean. The
Romans and the Goths, confounding it with the two historic
promontories of Europe and Africa, called the imposing structure
that supported it the Pillars of Hercules. But it certainly had no
connection with that divinity. His temple stood some miles away
upon an island, and it was the distinctive peculiarity of his worship
among the Phœnicians that he was never represented under a
physical form. To the Arabs the statue was known as “The Idol of
Cadiz.” A singular fatality had preserved it from the zeal and fury of
early sectaries of Islam. It had, no doubt, often awakened the pious
horror of devout pilgrims on their way to the shrine of the western
Mecca. It had stimulated the curiosity of the antiquary during the
scientific period of the khalifate. It had pointed the way to many an
invading squadron. It had witnessed the success or the failure of
many revolutions. The truculent Norman pirates had viewed its
gigantic dimensions with superstitious terror. In the sagas of
Scandinavia is preserved the tradition that St. Olaf and his
freebooters were, during the eleventh century, deterred from further
prosecution of their ravages on the coast of the Peninsula by a vision
which its presence inspired. Its immunity from the effects of
fanaticism is not less remarkable than its long exemption from the
violence of rapacious marauders. A great treasure was said to be
concealed beneath the foundations of the tower. It was also the
general belief—not confined to the Peninsula, but prevalent
throughout Europe—that this famous statue was of solid gold. Its
brilliancy, which had remained untarnished by exposure for so many
centuries, tended to confirm, if not to absolutely establish, this
opinion.
At last, in the twelfth century, the Admiral Ibn-Mamun, having
revolted against the Almoravides, caused the statue to be
overthrown and broken to pieces. The material was then discovered
to be bronze, but the gold with which it was covered brought twelve
thousand dinars, a sum now equal to a hundred and ninety-two
thousand dollars.
Relieved of all apprehensions from his most dangerous adversary,
Abd-al-Mumen attacked and captured in succession the great cities
of Africa. Fez offered a desperate resistance, but was taken by
damming the river by which it was traversed, until the pent-up
waters, bursting their bounds, swept away a large portion of the
walls. Mequinez, Aghmat, Salé capitulated. Then the siege of
Morocco was begun. To convince the inhabitants of his inflexible
purpose, the Almohade general caused a permanent encampment,
which resembled, in the regular and substantial character of its
edifices, a handsome and well-built city, to be constructed before its
walls. The enterprise was prosecuted with unusual pertinacity and
vigor. In a sally a large detachment of the Almoravides was decoyed
into an ambuscade and cut to pieces, and, with numbers sensibly
reduced by this catastrophe, the garrison confined itself for the
future to repelling the scaling parties of the enemy. The complete
investment of the city was soon followed by famine. The dead lay
everywhere in ghastly heaps. The living drew lots to decide who
should be sacrificed to provide a horrible repast for his perishing
companions. Such was the awful mortality that two hundred
thousand persons died of starvation and disease. Aware of the
inevitable consequences of surrendering to barbarians without faith
or mercy, the garrison contended bravely against hope and fortune.
Finally, some Mozarabe soldiers entered into communication with
Abd-al-Mumen, and it was agreed that a gate should be opened
during the disorder attending a general attack. At daybreak the
Almohades, eager for revenge and booty, swarmed into the city. The
scimetar and the lance completed the work which famine had not
had time to finish. Seventy thousand defenceless persons were
massacred. Even this frightful sacrifice did not satiate the besiegers’
desire for blood. For three days such scenes were enacted as could
only be tolerated among men insensible to motives of humanity and
ignorant of the laws of war. Abd-al-Mumen decapitated with his own
hand Abu-Ishak, the son and successor of Tashfin. The command
then went forth that not one of the hated sect should be spared.
Great numbers of women and children were slaughtered by the
savage conquerors and the survivors sold into slavery. Every mosque
was levelled with the ground as the only way to purify the houses of
God from the abominations of the heretical Almoravides.
Preparations were immediately made to erect upon their sites others
more extensive and magnificent, and Abd-al-Mumen, who all the
while had remained outside the gates, marched away to other
scenes of conquest.
A century had elapsed since Abdallah-Ibn-Jahsim had announced
to the tribesmen of Lamtounah his mission as the apostle of political
integrity and religious reformation. Based upon his teachings, and
supported by his military genius and the prowess of his followers, a
mighty empire had arisen. With incredible rapidity it had combined in
apparently indissoluble union contending nationalities, hostile
dogmas, antagonistic temporal interests. It had subjugated a great
part of the continent of Africa. It had reconciled the discordant social
and political elements which for generations had disturbed the peace
and diminished the power of the Moslem states of Spain. It had
checked the progress of Christian conquest. By its sweeping victories
it had revived the memory of the splendid achievements of the
Western Khalifate. The largest armies that had ever trodden the soil
of the Peninsula had marched under its banners. Its chiefs were,
without exception, men of signal ability. Some, it is true, were
destitute of experience in the art of government, but endowed with
rare executive talents; others were warriors of established renown;
all had exhibited in the exalted post to which they had been called
by fortune the qualities of great generals, diplomatists, legislators.
The genius of the last of that princely race, had his designs not been
frustrated by the Almohade revolution, promised the eventual
restoration of Moorish rule over much, if not all, of the territory
included in the kingdoms of Aragon and Castile. The rise and
progress of no dynasty to boundless power had been so rapid; the
decline of none had been more decided or its extinction more
destructive and fatal. Mohammedan Spain, still the most civilized and
polished of countries, whose court had once dictated the policy of
Western Europe; whose alliance had been assiduously courted by
Christian kings and emperors; whose armies marched each year to
victory; whose fleets monopolized the trade of the seas; whose
capital was the literary centre of the world, had been degraded to a
dependency of the most ignorant, the most superstitious, the most
brutal of nations. The hazardous experiment of establishing a
peaceable union between such incongruous and inimical populations
must have resulted in failure. Still less could such an undertaking
have succeeded when attempted by force. The ethnical elements of
Spain and Africa could never have coalesced into a single people.
Their enmity was irreconcilable. Their tastes were dissimilar. The
Hispano-Arab was a scholar, a philosopher, a gentleman. In spite of
the evils which afflicted his country, his colleges and academies were
still largely attended by the ambitious youth of distant, often of
hostile, nations. He still had access to the fragmentary remains of
the great libraries of the khalifs. The architectural monuments of his
ancestors still graced, in all their splendor and beauty, the
esplanades and thoroughfares of his capitals. Pilgrims still admired
with astonishment and rapture the most magnificent temple of
Islam. The sacred volume ascribed to the martyred Othman,
enshrined in its embossed and jewel-studded casket, still received,
amidst the lavish sculpture and sparkling enamels of the Mihrab, the
reverential homage of the Faithful. The diminished but not
unimportant commerce of his seaports; the manufacturing
establishments, whose products were largely exported to foreign
countries; the contracted but marvellously fertile area of his
agricultural territory, daily reminded the Spanish Moslem of the
wisdom and the enterprise developed by the subjects of that
glorious empire whose institutions, whose traditions, whose refined
tastes, whose intellectual pre-eminence he had inherited.
Far different was it with the conqueror who had appropriated and
abused the inestimable remains of all this greatness. From first to
last his movements seemed to have been inspired by the genius of
disorganization and ruin. The noble attributes of piety and
magnanimity were absolutely foreign to his nature. He spared no
foe. He forgave no injury. The essential doctrines of the religion he
nominally professed were in reality unknown to him. He was wholly
ignorant of letters. In the gratification of his savage passions the
shedding of blood took precedence of the grovelling instinct of
avarice or the more gentle allurements of licentious pleasures. His
stolid nature could not appreciate the charms of art, the benefits of
science, the delights and the consolations of literature, the
advantages of philosophy. All that did not contribute to sensual
enjoyment he turned from with disdain. Descended from a race of
brigands, who had from time immemorial exercised on the caravans
of the Desert the stratagems and the violence of their nefarious
calling, he considered the menial and sedentary occupations of
agricultural and manufacturing industry as only fit for the hireling
and the slave. Ever accustomed to individual freedom, he obeyed
only the orders of his sheik, who owed his promotion to the suffrage
of the tribe, and who was often elected or deposed with equal haste
and facility. The monarch was frequently as unlettered as his
meanest subject. Yusuf could neither read nor write, and understood
but imperfectly the copious and polished idiom spoken in many
provinces of his dominions. Ali was less intelligent than many a
youth in the primary schools of Cordova. This wide-spread and
deplorable contempt for learning virtually placed the power of the
state in the hands of a class least qualified to wield it; and the
intrigues and exactions of the Mohammedan clergy, supplemented
with African barbarism and rapacity, contributed more than domestic
convulsions or Christian valor to finally subvert the unstable but still
majestic fabric of the Saracen power.
The Moslem factions of the Peninsula joined in precarious union
under the sceptre of the Almoravides beheld with dismal forebodings
the successive and crushing misfortunes which preceded the
extinction of that dynasty. Neither religious accord nor political
necessity would have reconciled them to the domination of a race
between whose members and themselves there existed an
irreconcilable antipathy. But on many points of theological
controversy the liberal views of the most learned Moorish doctors
shocked the strict disciplinarians of Islam. These accomplished
polemical scholars had imbibed in the Universities of Seville and
Cordova ideas highly offensive to the severely orthodox; they had
indulged their wit at the expense of hypocrisy and ignorance in the
intellectual atmosphere of the court, and the vengeance of those
who were recently the objects of their satire had now descended
with redoubled force upon the thoughtless aggressors. All books
except the Koran and the Sunnah fell under the royal displeasure.
The study of philosophy, although prohibited in the schools, was, as
is usual under such circumstances, diligently pursued in secret. The
intellectual habits of centuries were not to be abolished by an
imperial edict, and the reprobation of a band of hypocrites and
zealots who preached self-denial and abstemiousness, and were
notoriously guilty of the grossest offences against morality, was
unable to entirely suppress the accumulation and the diffusion of
knowledge. No country in Europe, however, was more exclusively
and disastrously controlled by ecclesiastical influence than was
Moorish Spain under the rule of the Almoravides.
Aside from theological considerations, as has been previously
stated, universal dissatisfaction with the dominant race existed. The
Africans were regarded as foreigners, invaders, oppressors. They
had, even in their moments of leisure, contributed nothing to the
material wealth of the country. They were unacquainted with the
simplest principles of engineering or the adaptation of the
mechanical arts to the ordinary concerns of life. No structure worthy
of notice had risen under their auspices. Their native ferocity
remained unmitigated in the midst of the humanizing influences of
civilization. They discouraged manual labor and despised the
occupations by which that labor was employed and maintained. Thus
harassed by theological intolerance and barbarian tyranny, every sect
and party in the Peninsula, except the one in power, received with
secret exultation intelligence of the serious disasters to the
Almoravide cause. Public feeling was already aroused to a point
which almost defied restraint, when news arrived of the defeat and
death of Tashfin, whose well-known abilities and courage had
heretofore alone prevented a revolt. It was then that the long
suppressed and furious passions of an outraged people found
expression. In every Moslem community the mob rose against their
African tyrants. Ibn-Gamia, the lieutenant of Tashfin, fled to the
Balearic Isles. Complete anarchy prevailed. Governors of provinces
and commanders of fortresses aspired to independence. Each city
became the capital of a miniature kingdom, each castle the seat of a
principality. Forgetting the imminent peril in which they stood,
environed as they were by powerful enemies, these petty sovereigns
immediately turned against each other. Civil war of the most
sanguinary and vindictive character was inaugurated. Cordova
deposed her governor, installed another, and, after eight days,
recalled the first to power. At Granada the Almoravide garrison was
besieged for months in the citadel. In some provinces the inconstant
temper of the multitude, which selected and murdered their rulers
with equal alacrity, made the promotion to supreme authority,
usually so coveted by ambitious men, a distinction of the most
doubtful and invidious character. The Kadi of Cordova, whose office
retained to a considerable extent the dignity and importance with
which it was invested under the khalifs as the first judicial
employment in the empire, was assassinated while at prayer in the
mosque. The appearance of an African in the streets of any
Andalusian city immediately provoked a riot. The obligations of
hospitality were forgotten in the gratification of vengeance.
Obnoxious ministers were poisoned amidst the festivities of the
banquet. Military officers whose loyalty interposed obstacles to the
ambition of obscure and unprincipled adventurers were murdered
while asleep. The dangerous aid of the Christian princes, only too
willing to contribute to the mutual embarrassment and enmity of
their Mussulman neighbors, was invoked. Ibn-Gamia had succeeded
in organizing a considerable party of adherents, and had obtained
from Alfonso VII., King of Castile, a body of troops on condition of
the acknowledgment of the latter as suzerain. Baeza was the first
place to submit to Ibn-Gamia, and its surrender was immediately
followed by the siege of Cordova. In this singular warfare, Moslems
and Christians, although their efforts were directed against a
common enemy, fought and encamped apart, serving independently
under their respective commanders. The Castilians, conscious of
their power, treated their allies with undisguised contempt, and
haughtily ascribed to Christian valor alone the achievement of every
successful enterprise. The venerable capital, incapable of prolonged
resistance, soon opened its gates to the besiegers. The entry of the
Christians was rendered memorable by the commission of a sacrilege
in comparison with which the profanations of former conquerors
were trivial. The Great Mosque of Abd-al-Rahman, one of the holy
places of Islam, which since its foundation had never been profaned
by the presence of an infidel, was invaded by the rude Castilian
soldiery. They rode through its court, fragrant with the odors of
innumerable orange blossoms. They tethered their war-horses in its
arcades. They bathed in the basins whose waters had hitherto been
sacred to the ablutions of the Moslem ceremonial. Inside the edifice
raised by the tribute of Christian cities and the spoils of a hundred
victorious campaigns, they sauntered through the colonnades and
gazed with wonder upon the Mihrab blazing with all the gorgeous
magnificence of the East. The religious sentiments and prejudices of
their allies received no consideration at the hands of these scoffing
mercenaries. Despite the remonstrances of the Moslems, they
desecrated the precincts of the sanctuary. Some mounted the pulpit
and derided with indecent mockery the postures and genuflexions of
the Mussulman worship. Their eyes glared with unrestrained cupidity
upon the casket of sandal-wood and ebony enriched with gems
which contained the Koran of Othman. With flippant and sneering
comments they examined that volume, venerated by the Moslems of
every age and nation with all the superstitious reverence of idolatry.
They removed it from its receptacle, turned over its leaves, and
gazed with incredulity and contempt on the mysterious stains which
tradition and faith attributed to the blood of the murdered Khalif. In
their intercourse with the citizens their overbearing demeanor and
insatiable rapacity caused the encroachments of Moslem tyranny to
be almost forgotten. Their leaders, assuming all the credit of a
conquest in which they had figured in a subordinate capacity,
demanded that Cordova be added to the realms of Castile. This
proposition, repugnant to every sense of justice, was promptly
rejected by the Moslems. A serious altercation followed; the rival
captains mutually refused to yield, and a collision seemed imminent,
when through the adoption of prudent counsels matters were
adjusted by the cession of Baeza, which was immediately occupied
by a detachment of Christian troops.
The subjection of Africa by the Almohades had scarcely been
effected when Abd-al-Mumen began to take measures for the
establishment of his power in the Peninsula. An army of thirty
thousand soldiers, commanded by Abu-Amrah-Musa, landed at
Algeziras. The march of this formidable army resembled a triumphal
progress rather than the cautious movements of a hostile force. The
people, with characteristic inconstancy, welcomed the savage
invaders as the deliverers of their country. Algeziras, with its ample
port and well-provided magazines and arsenals; Tarifa, with its
impregnable defences; Xeres, with its wealth of orange groves and
vineyards, opened their gates to the enemy. Then Abu-Amrah,
flushed with success, pushed on to Seville. On the march his ranks
were swelled by numerous accessions from the peasantry, actuated
by the prospect of plunder and the hope of retribution. To these
undisciplined but serviceable recruits was added a considerable and
well-equipped reinforcement from the province of Badajoz. Seville
had remained nominally loyal to the Almoravides; but her population
was divided by faction, and thousands of citizens cherished in secret
implacable resentment against their cruel and avaricious masters.
Warning was conveyed to the garrison of the treasonable intentions
of the populace, which had promised to deliver the city to the
Africans, and it escaped to Carmona before the appearance of the
enemy. Seville was no sooner occupied than Malaga, always
susceptible to African influence, and whose inhabitants had probably
long been cognizant of the projected invasion, voluntarily submitted
to the Almohades and added another to their list of bloodless but
decisive triumphs.
The memory of the exploits of the Almoravide generals, and the
appearance of a new and victorious enemy in the South, had
reconciled the quarrels of the Christian states far more effectually
than all the concessions of diplomacy or the exhortations and
anathemas of the Church. Envoys from the Italian republics of
Venice, Pisa, and Genoa had recently visited the Castilian court and
represented to the King the important service he could confer upon
Christendom by the suppression of the pirates who, from their
stronghold at Almeria, threatened the destruction of commerce on
the Mediterranean. The depredations of these adventurous rovers
carried terror into every part of Southern Europe. Their vessels
swept the coast from Bayonne to Constantinople, defied the
combined navies of Italy and the Empire of the East, and had
already materially reduced the wealth and disturbed the trade of
many populous and important cities. It seems extraordinary that
under such circumstances application for relief should have been
made to the remote kingdom of Castile. It was separated from
Almeria by the entire length of the Spanish Peninsula. Vast tracts of
barren lands, provinces swarming with a hostile and warlike
population, were interposed between its plains and the tropical coast
of Andalusia. A formidable enemy had just established himself in the
most fertile districts of the South. The port of Malaga, in close
proximity to the destination of the expedition, was in his power. It is
true that the republics of Italy, united by a common faith and
sympathizers in a common cause, had long been allies of the
Christian kingdoms of Northern Spain. But something more than
hatred of the Moslem and devotion to the interests of the Church
must have impelled Alfonso VII. to undertake an enterprise of
certain difficulty and of doubtful success. A foe that had vanquished
a dynasty whose armies had repeatedly desolated his kingdom and
insulted his capital already menaced his borders. It is highly
probable that the Pope, influenced by temporal far more than by
spiritual considerations, may have proposed or even dictated the
terms of this alliance. It was no unusual thing for the Holy Father,
whose vow of poverty, like many other moral obligations, gave him
little concern, to share in the profits of commerce. The private
revenues of His Holiness, often inadequate to the prodigal
expenditures required for the pomp and luxury of the Vatican, could
easily be increased by mercantile speculations, and the Moorish
corsair in his indiscriminate depredations would certainly not respect
the property of the highest dignitary of a hostile faith. The character
of Eugenius III. gives color to this hypothesis. His court, under the
threadbare cloak of asceticism, was shockingly corrupt. The
institution of begging friars, the imposition of frequent penances, the
observation of fasts, the performance of pilgrimage, could not
conceal from the eyes of the least discerning the universal and
notorious profligacy which infected every profession and every class
of society in Rome. The avarice of the Pope himself was proverbial.
Blessings, indulgences, and absolutions, whose prices were
regulated by an established tariff, were sold by the clergy, and
wealthy or repentant sinners in multitudes availed themselves of the
facilities for wickedness or of the immunity from ecclesiastical
censure afforded by traffic in this spiritual merchandise. The
mercenary and grasping disposition of Eugenius was also
subsequently confirmed by his sale of Portugal to Alfonso Henriquez,
in flagrant contravention of the rights of the King of Castile. These
circumstances serve to explain the unprofitable siege of a distant
seaport by a power having no immediate interest in its subjugation,
when a vigorous campaign by the united Christians would in all
probability have prevented the renewed calamities of African
invasion and have materially accelerated the progress of the
Reconquest.
The sacred character of an enterprise openly patronized by the
Holy See, and directed by some of the greatest princes of Europe,
attracted volunteers from every country in Christendom. As usual,
the prospect of booty was a much more potent incentive than the
punishment of infidels or the propagation of the Faith. Almeria,
which, aided by its geographical situation, had had the good fortune
to escape the evils of conquest and anarchy that afflicted other
Andalusian cities, was still the seat of affluence and power. Under
the khalifate it had been the most populous and flourishing
emporium of Spain. Civil war, so far from impairing its prosperity,
had actually contributed to it. It still retained the manufacturing
establishments whose products were exported to the limits of the
civilized world. Many of the latter, such as pottery and silk, were
unequalled in quality and finish, and could nowhere else be
obtained. The proficiency of the artisans of Almeria in their
respective avocations was proverbial, and had been acquired by
experience and inheritance through many generations. The city
exhibited the political phenomenon of a Moslem republic; its affairs
were directed by a council presided over by a magistrate who,
without openly claiming them, exercised the prerogatives of an
absolute ruler. Its naval force could vie in numbers and strength with
that of the most formidable commercial state of the Mediterranean.
The practice of piracy had been so lucrative that the wealth and
population of Almeria had greatly increased, and the ancient walls
no longer sufficed to contain the innumerable houses of the citizens
and the villas of the aristocracy, which, environed by plantations of
tropical trees, extended for miles beyond the fortifications. The
citadel was one of the largest and strongest in Europe. While closely
connected by blood and sympathy with the nations of Africa, the
inhabitants of the city were independent of all factions, recognized
the pretensions of no dynasty, and acknowledged the authority of no
government save that of their own. A force not unworthy of an
Oriental crusade assembled for the conquest of this piratical
stronghold. The armies of Castile, of Leon, of Aragon, of Navarre,
the Counts of Montpellier and Catalonia, the combined navies of
Genoa, Pisa, and Venice, and thousands of soldiers of fortune,
serving in bands under their respective commanders, but without a
standard and without a country, responded to the crusading appeal.
No estimate of the allied host has come down to us, but its numbers
were so overwhelming that not a single Moslem prince dared to
assist his countrymen; and the Almerians, closely invested, without
means of defence and destitute of all hope of relief, after a two
months’ blockade surrendered. By the terms of capitulation, safety
of their persons was assured; an unusual concession in those times,
and one which indicates the introduction of a spirit of good faith and
humanity into the hitherto barbarous usages of war. The Italians, by
superior dexterity or assurance, obtained the larger share of the
spoil; the city itself, the most valuable prize, was allotted to the
Count of Barcelona, the proximity of whose dominions afforded the
best security for its retention as a Christian possession; and the King
of Castile, who had been the soul of the undertaking, and whose
followers had been over-reached in the division of booty, was forced
to be content with the conscious satisfaction of success and the
profuse but empty congratulations of the Holy See. The enterprise
achieved, the allied army dispersed with the unceremonious haste
characteristic of enlistments under feudal institutions. Deficiency of
experience and absence of discipline; impatience of the delay and
inaction implied by a lengthy campaign; the want of cohesion
exhibited by a force consisting of different nationalities and divided
by conflicting interests; apprehension of the storms of winter in an
unknown climate, dissipated in a day a force capable of the greatest
military exploits.
The thirty thousand Almohades who had occupied, almost without
bloodshed, much of the Andalusian territory, and were forced to
remain in inactivity behind the walls of the cities which had fallen
into their hands, viewed with surprise the vast preparations of the
Christians and the insignificant results of their campaign. The
numbers of the Africans, insufficient in themselves and distributed
among a score of garrisons, were unable to cope with the enemy,
and the present embarrassment of Abd-al-Mumen precluded the
hope of pecuniary aid or effective reinforcements. A new Mahdi had
arisen among the sands of Al-Maghreb. Of plebeian origin and
menial employment,—for he earned a livelihood washing garments
in the environs of Salé,—without learning or personal attractions, his
rude eloquence soon collected around him a numerous body of
disciples. The remains of the Almoravide faction, all those who were
dissatisfied with the present government, individuals allured by the
charm of novelty, thousands of proselytes, sincerely convinced of the
mission of the new prophet, repaired to the hostile camp. Before
Abd-al-Mumen fully realized his peril his armies had been beaten and
scattered, his ablest lieutenants killed, his dominions, acquired with
so much difficulty, seized by his rival, and his authority confined to
the cities of Fez and Morocco, whose populace, habituated to revolt
and disorder, could not be trusted. He was now enabled to
appreciate the inconstant and treacherous character of the nations
over whom he had established a nominal empire. Fortune, however,
proved in the end propitious to the chief of the Almohades; his rival
was defeated in a pitched battle and killed, and his fickle subjects
returned to their allegiance with the same enthusiasm with which
they had so recently renounced it.
In the mean time, after the capture of Almeria, the Christians
began again to exert their power in every Moslem province of the
Peninsula. The Count of Barcelona, supported by the Italian fleets,
invested and took Tortosa, which commanded the mouth of the
Ebro. Its submission was followed by the conquest of Lerida, Fraga,
and Mequinenza, and the great river of Aragon, now open to the
sea, marked for a brief period the gradually contracting boundary of
the Moorish possessions of Eastern Spain. The rising monarchy of
Portugal, for the first time beginning to assert itself among nations,
acquired renewed prestige by the capture of Cintra and Lisbon. The
movements of Ibn-Gamia, whose valor and activity still sustained the
sinking fortunes of the Almoravide cause, stimulated the Almohades
to exertion. Worsted in several encounters, he retired to Cordova,
but, unable to maintain his ground, he placed his lieutenant Yahya in
command and effected a retreat by night after the Almohades had
encamped before the city. Yahya, by a prompt submission, averted
the carnage which in these wars inevitably followed a protracted
defence, and the ancient metropolis of the khalifate once more
submitted to the rule of a foreign master. In the Great Mosque, the
scene of so many triumphs and humiliations, which had witnessed
the installation of a long succession of Moslem princes, the public
exhibition of the trophies of conquest, the murder of magistrates,
the tumults of revolution, Abd-al-Mumen was proclaimed Emir of the
Mussulmans of Spain. The fierce spirit of the invaders seems to have
been restrained by the dangers of the situation, the uncertainty of
support, and the activity of the Christians, considerations which
rendered leniency towards the vanquished not only politic but
necessary. Carmona was soon added to the Almohade conquests
and Ibn-Gamia fled to Granada, where he afterwards fell in battle.
His partisans then espoused in a body the cause of Alfonso of
Castile. With this open defection the condition of the Spanish
Moslems became more desperate. Divided among themselves, with
half of their best soldiers fighting under the banners of their
hereditary foe, apparently abandoned by the prince raised to
imperial power in the religious centre of the kingdom, without
resources, without prospect of assistance, nothing but the presence
of the Almohades preserved the relics of the khalifate from
immediate absorption by the kingdoms of Castile and Aragon.
Finally, Abd-al-Mumen, having consolidated his empire in Africa, and
moved by the entreaties of his Andalusian subjects, who sent a
deputation of five hundred citizens to invoke his aid, despatched an
army under his son Abu-Said to the Peninsula. The city of Almeria,
whose situation, in a strategic point of view, commanded the coast
of Africa, was the object of the expedition. The siege having been
formed, an ineffectual attempt was made by Alfonso for the relief of
the garrison, after which it was abandoned to its fate. The forces of
Abd-al-Mumen not being able to blockade the port, it was found
impossible to reduce the place by famine, and the strength of the
fortifications precluded all hope of taking it by storm. The patience
and endurance of the garrison, however, were exhausted by
constant alarms and by the indefatigable perseverance of the enemy,
and the Moslems, after an exclusion of ten years, regained
possession of the most formidable stronghold of Andalusia.
This decisive success was supplemented by other and scarcely
less important achievements. The populous city of Niebla, a
dependency of Seville, was stormed by Abu-Zacaria, who had been
one of the Almohade commanders during the former invasion. Its
stubborn resistance provoked the commission of the greatest
barbarities in the hour of triumph. No male of mature years survived
the carnage of the assault. In compliance with the customs of
Berber warfare, the children were destined for the slave market, the
women for the seraglio. Such was the unbridled fury of the
conqueror that in a single suburb of the ill-fated city eight thousand
victims of African savagery paid the last penalty of defeat. The arms
of the Almohades were now turned against Granada. That capital,
after a short and bloody resistance, was carried by the troops of
Abu-Said, and the horrors of Niebla were repeated upon the
Christian garrison, who atoned with their lives for the ill-advised
alliance of the last representatives of the Almoravides with the
sovereign of Castile. The capture of Granada marks the final descent
from power of that party whose tyranny and depredations had for
almost a generation disturbed the peace of the Peninsula.
The experience of Abd-al-Mumen with treacherous vassals and
daring impostors made him reluctant to leave his capital, constantly
exposed to revolution, for the sake of confirming his power over the
Moslem states of Spain. And, indeed, there seemed to be but little
necessity for his personal appearance in Andalusia. In addition to the
native auxiliaries there were now fifty thousand Almohade veterans
in that country. His generals had demonstrated their ability for
command on many fields of battle. The principal cities of the South
—Cordova, Seville, Carmona, Granada, Malaga, Almeria, Badajoz—
were garrisoned by his troops. His armies had as yet sustained no
repulse; the most fertile districts furnished them with abundant
subsistence; a considerable tribute was collected from the Jews and
Mozarabes, who were compelled to pay liberally for privileges and
protection which they did not enjoy; Alfonso VII., the most
redoubtable enemy of the Moslems, had recently died, and the other
Christian princes, doubtful of their strength, hesitated to confront
the victorious Almohade squadrons. Although determined not to
imperil his crown by a prolonged absence from his capital, Abd-al-
Mumen paid a visit to Gibraltar, which he strongly fortified, and
where he received the homage of the various officials of his recently
acquired dominions.
Almost simultaneously with the disappearance of the Almoravides
a new champion of Hispano-Arab independence arose in the east of
the Peninsula. Mohammed-Ibn-Saad, Prince of Valencia, attempted,
but without success, to oppose the authority of the hated Africans.
Routed before Granada, he organized another army in the Alpujarras
and, reinforced by a body of Christians from Toledo, again tried the
fortunes of war under the walls of Cordova. The bravery of the
Andalusians availed little in the presence of the invincible veterans of
Abd-al-Mumen. They were cut to pieces, and their leader, Ibn-Saad,
escaping with difficulty, fled to Murcia.
The martial spirit of Abd-al-Mumen was not enfeebled either by
increasing physical infirmities or by the accumulated weight of years.
The unsettled state of affairs in Spain and the unsatisfactory results
accomplished by his generals, whose victories, however brilliant,
seemed to inflict but trifling injury on the enemy, convinced him of
the necessity for an aggressive and decisive campaign. The
innumerable tribes, provinces, and kingdoms of Africa united under
his sceptre had submitted without murmur or hesitation to the
exercise of despotic power. The wisdom of his administration, the
severity with which rebels and outlaws were punished, diffused a
wholesome dread of his anger throughout the vast Almohade
monarchy, more extensive even than that ruled by any of his
predecessors and reaching from the Mediterranean to the south of
the Sahara, from the Atlantic to the valley of the Nile. Supplies
sufficient for the maintenance of an immense army were collected at
Tangier, Algeziras, Gibraltar. Then the proclamation of the Holy War
was issued. There responded to that welcome summons nearly half
a million men. But before they could be assembled and organized for
action, Abd-al-Mumen expired, bequeathing his throne and the
execution of his projects of ambition to his third and favorite son,
Abu-Yakub-Yusuf, a prince eminently worthy of the responsibilities
imposed upon him by paternal favor and the caprice of fortune.
The character of Abd-al-Mumen presents an epitome of the
homely virtues and ferocious vices of the Desert. In the attainment
of his ends he was seldom swayed by considerations of pity, honor,
or benevolence. He never shrank from indiscriminate butchery in the
heat of battle. He seldom hesitated to pardon a defeated and
submissive foe. In the dispensation of justice the culprit promptly
underwent the extreme penalty of violated law. The attention of the
founder of a stupendous empire was not entirely engrossed by
schemes of war and conquest. He established schools and colleges
in the larger cities of his dominions, fostered literature, encouraged
art. The most talented and accomplished teachers in the entire
realm of Islam were attracted to his court, where, honored with the
friendship and enriched by the liberality of their royal patron, their
efforts were directed to the education of youth. Three thousand of
the latter, selected from the most distinguished families, were
assembled in a university at the capital, where they not only profited
by the instruction of learned professors, but were daily exercised in
the military evolutions essential to a competent knowledge of the art
of war—the manœuvring, the encampment, and the discipline of
armies. Under the care of such a monarch the city of Morocco
became a metropolis worthy of an empire which comprehended an
hundred distinct tribes and nations, and whose opposite boundaries
were separated by a four months’ journey. The royal residence and
its gardens enclosed a vast area beautified by every resource of art
and luxury. The inventive genius of skilful foreign artisans had
provided both palace and mosque with many appliances of
wonderful ingenuity,—doors which opened and closed apparently
without human agency; pulpits and tribunes which, acting
automatically, moved to and fro impelled by hidden mechanism;
fountains whose jets, mysteriously controlled by valves and springs,
were the perpetual delight and wonder of the people.
Under his administration hundreds of vessels were constructed;
the navy-yards were enlarged and increased in number, and
powerful fleets bearing the white standard of the Almohades
maintained the dignity of the Sultan of Africa and Spain in every
quarter of the Mediterranean.
The long reign of Abd-al-Mumen, who governed Spain entirely
through his viceroys, was not less injurious to the interests of that
country than the domination of the Almoravides had been. The
plague of civil war, the menace of Christian conquest, the evils of
revolution and anarchy, the ferocity of the remorseless conqueror,
with whom resistance was an offence only to be expiated by death
or slavery, were conditions fatal to agricultural and commercial
prosperity. Moorish Spain, once the proud mistress of the Occident,
the seat of learning and the arts, now the sport of fortune and the
prey of savage hordes nurtured amidst the African deserts, was, with
the passage of each decade, rapidly descending in the scale of
civilization. Her political influence and the prestige of her name had
disappeared. The wealth accumulated under the beneficent rule of
the Ommeyade dynasty had either been dissipated in luxury or been
borne away by barbarian invaders. The time was almost at hand
when a religious tyranny, more grievous in its burdens, more cruel in
the inexorable severity of its decrees, than the worst examples of
African despotism, was to be imposed on the descendants of a
people which had made the Western Khalifate the seat of the most
opulent, the most intellectual, the most powerful of nations.
Yusuf, the new Sultan of the Almohades, distrusting the loyalty of
his subjects, and apprehensive of a disputed succession, had no
sooner ascended the throne than he disbanded the great army
collected by his father for the subjection of the Peninsula. A well-
balanced and discriminating mind, an excellent education acquired
under the direction of the most learned doctors of the age, unusual
proficiency in the martial exercises practised with such assiduity by
the Mauritanian youth, considerable experience in the arts of policy
and in the conduct of campaigns, admirably fitted Yusuf for the cares
of government. The summary measures adopted by his father to
maintain public security, and his own well-established reputation for
ability and resolution, preserved his accession from the dangers of
revolt. A few insignificant demonstrations by the restless tribes of
the Atlas, which were speedily and mercilessly repressed, disturbed
the first few months of his reign. But no pretender rose to dispute
his claims to sovereignty; no prophet ventured to arouse the
credulous and fanatical swarms of the Desert; no concerted
movement of discontented chieftains threatened the permanence of
a monarchy which had been founded on revolution, and whose
history had been marked by incessant turmoil and sedition. Satisfied
with the peaceful condition of his African possessions, Yusuf, having
sent to Spain twenty thousand of his choicest troops, after a short
delay followed them, and, assuming the supreme command,
established his residence at Seville. The discord existing between the
petty rulers of the Moslem states, whose enmity was the more
decided in proportion to their incapacity to indulge it, operated in the
most signal manner to the advantage of his cause. Ibn-Saad, lord of
Eastern Spain, whose kingdom included the cities of Murcia,
Valencia, Alicante, Xativa, Denia, Lorca, many flourishing villages,
and the most fertile portion of the Peninsula, was killed in an
expedition to Minorca, and his sons, unable to defend their rich
inheritance against both the Aragonese and the Almohades at once,
entered into negotiations with Yusuf for the exchange of their
territories for others less valuable, perhaps, but more secure, on the
shores of Northern Africa. The bargain was soon concluded. The
Murcian princes, eager to dispose of what they must otherwise
inevitably lose, embarked for their new dominions; the daughter of
Ibn-Saad, a pledge of the contract, became the wife of Yusuf, and
the most valuable district in Spain—when the productiveness of the
soil, the wealth and commercial advantages of the cities, and the
density and industrious character of the population are considered—
passed, without the hazards of a campaign or the loss of a single
drop of blood, under the control of the Sultan of the Almohades.
It was not, however, by the peaceable arts of diplomacy alone
that additions were made to the empire of Yusuf. In the west,
Badajoz, repeatedly captured and retaken by Christian and Moslem,
was occupied by his troops. At the head of a column of several
thousand cavalry he ravaged the valley of the Tagus as far as the
suburbs of Toledo. The border stronghold of Alcantara, long vaunted
as impregnable, submitted to his arms. Nor was it on account of his
military exploits that the name of Yusuf has been transmitted to the
admiration of posterity. Although he passed but a year in the most
enchanting of Andalusian cities, the evidences of his presence are
to-day the principal, almost the sole, attractions of that beautiful
capital. The memory of his genius and munificence have been
perpetuated by the erection of quays, palaces, towers, whose
stupendous dimensions are now the wonder of the modern engineer,
and of mosques whose minarets were once incomparable models of
architectural symmetry and elegance. He repaired and enlarged the
Roman aqueduct, which still conducts from the springs of Alcalá the
purest water for the use of Seville. He spanned the Guadalquivir with
a bridge of boats, the counterpart and predecessor of the one which
until within a century united the opposite banks of that broad and
rapid stream. Its inundations, which had previously damaged
property and imperilled life, were partially controlled by the
construction of gigantic walls, which arrested the destructive torrent
and turned it again into its proper channel. These structures served
as quays, which, approached from the river-side by broad and easy
stairways, greatly facilitated the unloading and shipment of
merchandise. Near at hand were warehouses and magazines
designed and erected by Yusuf, and whose convenience and capacity
were not surpassed by those of any Mediterranean seaport. The
defences of the city also claimed the attention of this wise and
indefatigable monarch, whose care and vigilance no detail, however
insignificant, seemed to escape. The ancient walls were repaired and
new ones constructed. Numerous towers were added to command
the river, among them the peculiar one now known as the Tower of
Gold, where was once kept the royal treasure. In the heart of the
city, and on the site of an ancient Christian church, a great mosque
was founded. The plan was a rectangle of four hundred and fourteen
by two hundred and seventy feet, and, although it could not in
justice be considered a rival of that noble edifice, it was in many
respects not far inferior to the peerless Djalma of Cordova. Its walls
were fringed with Persian battlements and painted with many colors.
Its arcades looked upon a court supplied with ever-murmuring
fountains and fragrant with the odor of orange blossoms. Its
hundreds of marble columns suggested the spoliation of many a
Pagan temple. The ceiling was formed by domes of wood and
stucco, whose geometrical patterns disclosed the correctness of
taste and inexhaustible fertility of fancy characteristic of the labors of
the Arab artist and gilder. Its mosaic pavements, its alabaster
lattices, its curious arabesques presented finished types of Moorish
decorative splendor nowhere more conspicuous than in his places of
religious worship. At one corner of the building rose a minaret of
moderate height but elaborate ornamentation, and diagonally
opposite were laid the foundations of that famous tower now known
as the Giralda, which, completed during the reign of the successor of
Yusuf, still remains the finest specimen of Moslem architecture of its
class in the world.
It was not alone in the improvement of his Spanish capital that
the time and energy of the Almohade Sultan were expended. The
military and naval advantages of Gibraltar had been early
appreciated by the sovereigns of Africa. Its fortifications were now
greatly extended and strengthened by the provident foresight of
Yusuf, who recognized in its peculiar and impregnable situation the
security of the Strait and the key of the Peninsula.
Summoned to Africa by the ravages of a pestilence which
decimated the population of his kingdom, ignorant of medical
knowledge, and abandoned to fatalism and the ministrations of
charlatans, Yusuf was compelled to suspend the public works which
had already produced such beneficial results amidst the decaying
commerce and diminishing resources of Andalusia. The absence of
the monarch became, as usual, the pretext for anarchy. With his
departure the quarrels of ambitious governors of provinces and the
harassing forays of the Christians were renewed. For the long period
of eight years this condition of incessant and ruinous hostility
continued. Then Yusuf resolved to accomplish the design matured by
his father, but whose execution had been prevented by death. The
Holy War was proclaimed. The forces of Africa were assembled at
Ceuta, and Spain was invaded by one of the largest armies that had
ever been marshalled on her soil. It is with interest that we read of
the orderly but undisciplined progress of this great array. The tribes
marched separately under their several sheiks. Each tribe carried its
distinctive standard—the ensign of that which constituted the
vanguard, the post of honor, was of blue and white silk spangled
with golden crescents. In the centre of the host rode the monarch,
surrounded by his negro guard, in whose equipment had been
lavished all the wealth of barbaric magnificence. Before him was
carried, as a talisman to insure success, the great Koran of Othman,
which, having escaped the perils of many revolutions, had been sent
to Morocco by the Almohades after their capture of Cordova. It was
escorted by a company of a hundred Berber nobles, mounted upon
superb Arabian horses whose velvet housings were embroidered
with gold. This guard of honor carried lances inlaid with ivory and
silver, from which fluttered pennons of many-colored silk. The casket
in which was deposited the most priceless relic of Islam was the
same which had been adorned by the emulous devotion and
prodigality of many generations of Moslem princes. Its material of
ebony and sandal-wood was entirely concealed by the multitude of
jewels with which it was encrusted. The greater part of these were
emeralds and rubies, and were kept in place by heavy settings of
gold. They were arranged in arabesques, and in the centre of each
design sparkled a magnificent ruby cut in horseshoe form. The
casket was lined with green silk and cloth-of-gold, and a covering of
the same material sowed with pearls and other precious stones
concealed the treasure from the eyes of the multitude. Its weight,
which was far from inconsiderable, was supported by a stately
camel, whose burden was sheltered by a canopy on which were
emblazoned in golden letters appropriate legends from the Koran. In
the rear of the Sultan came the princes of the blood, the royal
tributaries, and the grand officials of the empire. Seventy thousand
infantry and thirty thousand cavalry composed the available force of
the invaders, whose ranks were further augmented by at least a
hundred thousand slaves and dependents. The army moved in four
divisions, a day’s journey apart; at each halting-place provisions and
forage had been collected, and the perfection of these
arrangements, as well as the order maintained on the march,
attested the military skill and executive ability of the Moslem
general.
At Seville, designated as the rendezvous of the Spanish
contingent, Yusuf was joined by several thousand Berber troops,
who had served through many campaigns in the Peninsula. He then
crossed the frontier of Portugal and besieged Santarem. This city,
situated about fifty miles from Lisbon, was regarded as the bulwark
of that capital. It was on the point of being taken, when Yusuf was
surprised by an unexpected sally of the besiegers and mortally
wounded. The Moslems, goaded to madness by this misfortune,
drove back the attacking party, entered the gates with the fugitives,
and ten thousand persons, massacred amidst the horrors of the
unequal conflict, expiated the temporary and fatal success of a
handful of their number. The death of the Sultan, which, to avoid
political complications and civil war, was kept a secret, and did not
become publicly known until his successor, Abu-Yakub-Ibn-Yusuf,—
the ablest of his many sons, and who assumed the title of Al-
Mansur-Billah,—a few weeks afterwards ascended the throne. The
traits of Yusuf were those of a liberal, a just, a devout, a
magnanimous ruler. He reduced taxation. He increased the imperial
revenues. His inexorable severity was the terror of malefactors.
Before his tribunals no suitor could complain of judicial oppression or
venality. Under his administration, as under that of his father, the
clergy were restricted to the performance of their religious duties,
and were not permitted to usurp the functions or to absorb the
revenues of the civil power. The cities were patrolled by a well-
appointed and vigilant police, and law-abiding citizens were assured
of protection. The banditti disappeared from the highways before the
untiring pursuit of the authorities, who crucified every brigand as
soon as he was captured. Never since the most flourishing days of
the Ommeyade empire had the people of Moorish Spain enjoyed
such security.
According to Moslem custom, Yakub signalized his ascent to the
throne by acts of public charity and benevolence. He caused to be
distributed as alms the sum of a hundred thousand pieces of gold.
He increased the compensation of such officials as had honestly and
faithfully administered the public service. The taxes of the poor were
remitted, the tributes of the wealthy were reduced. The prisons were
cleared of all offenders except such as were accused of capital
crimes. Upon every magistrate was sedulously impressed the
necessity for the strict yet merciful enforcement of the laws. The
army was placed under better discipline, the pay of the soldiers was
increased, and the sanitary conditions of the barracks and the camp
improved. In both Spain and Africa new fortresses were erected at
points peculiarly exposed to the incursions of an enemy. Great sums
were expended in the improvement and the construction of
highways, and the bridges were placed in perfect repair, that no
obstacle might exist to the rapid movement of couriers or to easy
military communication between the seat of government and the
frontiers of the empire. At regular intervals along these
thoroughfares, wells were dug and stations established for the
shelter of travellers and the convenience of troops. The obligations
of religion and the demands of knowledge were not neglected by
this devout and generous ruler. Mosques, richly adorned, were built
in every considerable town and city, and attached to them were
institutions of learning, where gratuitous instruction was furnished to
the poor but aspiring student. The sufferings of the afflicted were
relieved by the establishment of hospitals, presided over by
physicians and surgeons thoroughly versed in the medical science of
the age. To such a degree had the traditions and example of the
Western Khalifate awakened the noble emulation of the greatest
prince who ever traced his origin to an African ancestor.
The commencement of the reign of Yakub, like those of his
predecessors, was distracted by war and sedition. The remains of
the Almoravide faction, established in the Balearic Isles, instigated
by delusive representations the tribes of the Desert and the
malcontents of the Peninsula to insurrection. Their efforts were,
however, incapable of seriously endangering the power of Yakub.
The leaders were arrested, and the adoption of the most energetic
measures soon restored the public tranquillity. The repentant
Berbers implored with success the royal clemency; and two of the
brothers of the Sultan, involved in the common guilt, were sacrificed
to the stern demands of justice and fraternal indignation.
At the head of a splendidly appointed army Yakub then passed
into Spain. At his approach, all who had wavered in fidelity or had
taken up arms hastened to solicit forgiveness and renew their
obligations of fealty. The expedition, which was merely a
reconnoissance, penetrated without difficulty as far as Lisbon. The
degree of its success may be inferred from the fact that the booty is
said to have exceeded in value any heretofore secured by any
foreign invader in the Peninsula excepting Musa, and that the
captives who followed in the train of the conqueror amounted to the
respectable number of thirteen thousand.
The crusading spirit, then at its height in Europe, soon offered the
King of Portugal an opportunity for retaliation. A large body of
Flemish and English knights and men-at-arms, on their way to the
Holy Land, disembarked at Lisbon to avoid, during the winter
months, the inconveniences of a protracted voyage and the
proverbial dangers of the Spanish coast. These adventurers accepted
with avidity the tempting proposals of the Portuguese king. The
Moorish territory was invaded by the crusaders, co-operating with a
force of native troops; and the cities of Evora, Beja, and Silves
became the prey of the most licentious soldiery in Europe. The latter
place, which had surrendered under articles of capitulation to
Sancho, King of Portugal, was, in violation of the laws of war and of
every principle of justice, abandoned to the tender mercies of the
foreigners. Out of a population of sixty thousand barely one-fifth
escaped with life and liberty. The majority of these were Jews,
whose commercial relations with the countries of Western Europe
gave them influence with the Christian commanders, while the
presence of numbers of their countrymen in the enemy’s camp
contributed in no small degree to their security. This immunity was
not obtained, however, without the payment of an exorbitant
ransom; the city was pillaged amidst indescribable scenes of cruelty,
and many of the crusaders, renouncing the pious cause in which

You might also like