《Java语言程序设计》期末复习

本文是针对《Java语言程序设计》期末考的要点复习,归纳了一些常见的基本考点,对知识点做了一个大致的梳理。(因为博主是全英考试,所以比较多英文)

目录

Chapter 1

1.1 Introduction to Java

1.2 Keywords and Identifiers

1.3 Data types

1.4 Variables and Constants

Chapter 2

2.1 Input and Output

2.2 Selection

2.3 Loop

Chapter 3

3.1 Java Objects and Classes

Chapter 4

4.1 Arryas

4.2 ArrayList(动态数组)

Chapter 5

5.1 Java pass by value

5.2 String

Chapter 6

6.1 Inheritance and access modifier protected

6.2 Composition

6.3 Polymorphism多态

Chapter 7

7.1 Abstract classes

7.2 Interface

Chapter 8

8.1 Advanced methods and concurrency

8.2 Exception handling

8.3 User-defined exceptions

Chapter 9

9.1 Introduction to graphical user interfaces (GUI)

9.2 Using top-level containers in Swing

9.3 Using layouts an buttons in Swing

Chapter 10

10.1 Event listeners and event handlers

Chapter 11

11.1 Models in Swing

11.2 Using JList and JTable with models

11.3 Basics of concurrency(并发) 

11.4 Concurrency with Swing

Chapter 12 

12.1 Reading and writing to text files

12.2 Formatted file writing and reading

12.3 Serialisation and deserialization

12.4 Functional programming and streams

Chapter 13

13.1 Generics (泛型) in Java

13.2 Queues and sets

13.3 Maps and comparators


Chapter 1

1.1 Introduction to Java

  • JVM (Java Virtual Machine)

JAVA有跨平台性,即平台独立性,原因是JVM。

通过执行javac命令把.java的源文件编译为.class文件。.class文件可以在JVM上运行,所以可以跨平台。

The JVM is a program that provides the “runtime environment” (or executed environment) necessary for Java programs to execute.

To compile .java file to .class file, use javac Program.java

To run .class file, use java <arguments> Program

1.2 Keywords and Identifiers

keywords就是关键字,也叫保留字。

Identifiers就是标识符,给类、变量和函数的命名。

Identifiers不能和keywords重复。

Java is a case-sensitive programming language.

1.3 Data types

Data types in Java refer to an extensive system used for declaring variables or functions of different types.

引用数据类型是建立在八大基本数据类型基础之上,包括数组、接口、类。引用数据类型是由用户自定义,用来限制其他数据类型。简单地说,除了八大基本类型之外都是引用数据类型。所有引用类型的默认值为null。

1.4 Variables and Constants

  • Declaring classes and methods

The basic syntax(句法) for declaring a class:

The basic syntax for declaring methods (inside classes):

  • Declaring variables in Java

In Java, variables need to be declared before using them.

Basic syntax for declaring a variable with default value:

Basic syntax of declaring a variable and assigning it a value:

By convention, variable-name identifiers in Java use the camel-case naming convention with a lowercase first letter (e.g. firstNumber).

Java运算符

运算符说明

. [] () {} , ;

分隔符( . 表示调用)

++  --  ~  !

单目运算符(~表示按位取反,!表示逻辑非)

(type)

强制类型转换运算符

*  /  %

乘法,除法,求余

+,-

加法,减法

<<  >>  >>>

移位运算符

<  <=  >  >=  instanceof

关系运算符

==,!=

等价运算符

&

按位与

^

按位异或

|

按位或

&&

逻辑与

||

逻辑或

?:

三目运算符

=,+=,-=,/=,*=

赋值,复合赋值

Chapter 2

2.1 Input and Output

  • Input

Scanner scanner = new Scanner(System.in);

读入一个整数  price =scanner.nextlnt()

读入一个字符串单词(以空格分隔判断)  word = scanner.next(); 

读入一整行 line = scanner.nextLine();

Similarly, we can use nextLong(), nextFloat(), nextDouble()

  • Output

System.out.println(“hello”);  输出一行文字(后面换行)

System.out.print(“hello”);    输出文字(后面不换行)

System.out.printf(“i的值是%d, j的值为%f, %s”, intNum, doubleNum, str);

2.2 Selection

  • if … else
if (studentGrade >= 90) {
    System.out.println("A");
}
else if (studentGrade >= 80) {
    System.out.println("B");
}else if (studentGrade >= 70) {
    System.out.println("C");
}else if (studentGrade >= 60) {
    System.out.println("D");
}
else {
    System.out.println("E");
}

  • switch … case

2.3 Loop

  • While

do … while

do {
    System.out.printf("%d", counter);
    ++counter;
} while (counter <= 10);
  • for

Chapter 3

3.1 Java Objects and Classes

A class specifies the state and behavior that an object can have.

-- State – What the object is

class fields (aka member fields, class members, class attribute etc) 类字段也就是类属性

The values contained in these variables is known as the object state.

       A class field is a variable which is accessible to all methods in the class.

-- Behavior – What the object does.

methods (aka submodules, functions)

Java只是在类中声明变量,赋值在constructor里。

  • Constructors

Constructors are the methods used to create an object.

  • Accessor/Interrogative Methods (访问器/询问方法)

“getters“ 方法

Accessor methods are used to retrieve information form the object.

// method to retrieve the name from the object
public String getName() {
    return name;  // return value of name to caller
}

Other Accessors

A convention is that all classes should have an additional two accessors:

-- equals (类似于python的__eq__()方法,重写改变判断相等的逻辑)

-- toString  (类似于python的__str__()方法,重写改变输出类的内容)

  • Mutator/Informative Methods(修改器/信息方法)

“setters”方法

Mutator methods are used to send information into the object which is used to modify the values of class fields.

// method to set the name in the object
public void setName(String name) {
    this.name = name; // store the name
}
  • Methods’ local variables (this)

The method’s body can use the keyword “this” to refer to the shadowed in stance variable(隐藏实例变量) explicitly.

  • key words static, final Types

A static field (called a class variable) is used in the case of only one copy of a particular variable should be shared by all objects of a class.(类变量,可以用<类名>.<变量>来访问或修改。任意修改一个实例的类变量会同时修改所有实例的类变量。类变量可被类中所有方法调用)

Static class members are available as soon as the class is loaded into memory at execution time.

     Private static members只能用 <类名>.<变量> 来调用

     Public static members能用 <类名>.<变量> 或者 <实例名>.<变量> 调用

静态方法:是使用static关键字修饰的方法,又叫类方法。属于类的,不属于对象,在实例化对象之前就可以通过类名.方法名调用静态方法。

(静态属性,静态方法都是属于类的,可以直接通过类名调用)。
A. 在静态方法中,可以调用静态方法。
B. 在静态方法中,不能调用非静态方法。
C. 在静态方法中,可以引用类变量(即,static修饰的变量)。
D. 在静态方法中,不能引用成员变量(即,没有static修饰的变量)。
E. 在静态方法中,不能使用super和this关键字

非静态方法:是不含有static关键字修饰的普通方法,又称为实例方法,成员方法。属于对象的,不属于类的。(成员属性,成员方法是属于对象的,必须通过new关键字创建对象后,再通过对象调用)。
A. 在普通方法中,可以调用普通方法。
B. 在普通方法中,可以调用静态方法
C. 在普通方法中,可以引用类变量和成员变量
D. 在普通方法中,可以使用super和this关键字

A final variable cannot be modified by assignment after it’s initialized

Chapter 4

4.1 Arryas

-- What are arrays?

       An array is a group of variables containing values that all have the same type.

-- Declaring and Creating Arrays

  • One-Dimensional Arrays:
int[] c = new int[12];
 int[][] array1 = {{1, 2, 3}, {4}, {5, 6}};

4.2 ArrayList(动态数组)

Arrays do not automatically change their size at execution time to accommodate additional elements, while ArrayList<T> (package java.util) can dynamically change its size to accommodate more elements. (T is a placeholder for the type of element stored in the collection.)

import java.util.ArrayList;
private ArrayList<String> notes = new ArrayList<string>();
//以上创建了一个存放String类型数据的容器,ArrayList是容器的类型,String是元素的类型

ArrayList的操作(假设有一对象notes)

1. notes.add(element);     //将一个元素加到最后

2. notes.add(index,element);    //将一个元素插入到index的位置

3. notes.remove(index);    //将index位置的元素删除,后面元素自动补位

4. notes.get(index);    //查找index位置的元素

5. notes.size()    //得到元素个

6. notes.clear()    //删除ArrayList中所有元素

7. notes.contains(element)   //如有存在element,返回ture;否则返回false

8. notes.indexOf(element)    //返回element第一次出现的下标

9. 将ArrayList中所有元素放入一个数组中

    String[] a = new String[notes.size()];

    notes.toArray(a);

10. System.out.println(notes);   //可以直接以数组形式输出所有元素

Chapter 5

5.1 Java pass by value

destructive操作指在内存中修改或删除数据的操作

nondestructive操作指对内存数据进行读取、查询或复制等操作。

  • Pass-By-Value vs Pass-By-Reference

Pass by value –-- a copy of the argument’s value is passed to the called method. 方法只对复制的数据操作,不影响原数据。

Pass-By-Reference ---- the called method can access the argument’s value in the caller directly and modify that data.对原数据进行操作

 All arguments are passed by value in Java

  • Deep copy method

clone() will take attribute values and not just create another reference to the object.

5.2 String

  • Constructor

String s1 = new String();

String s2 = new String(s);

String s3 = new String(charArray);

String s4 = new String(charArray, 6, 3);

String objects are immutable(不可变的) after it is created.

  • String methods

str.length()  获取字符串长度

str.charAt(index)  返回在index上的单个字符

str.getChars(srcBegin, srcEnd, dst,dstBegin)  将字符串中的字符复制到一个字符数组中。srcBegin是字符串起始索引,srcEnd是字符串结束索引,dst是目标字符数组,dstBegin是目标字符数组的起始索引(从这个位置开始保存复制的字符)

  • Comparison

==,equals(),compareTo()

== compares references

equals() compares values

compareTo() compare two strings lexicographically

  • String extracting

str.substring(endindex) 从指定索引截取到结尾

str.substring(startindex, endindex) 截取str的部分内容

Chapter 6

6.1 Inheritance and access modifier protected

1. 继承的概念: Class inheritance lets us declare classes that inherit common structure from higher level classes.

Objects of an inherited class can use the member variables and methods from the class it inherits.

2. Superclasses(parent) and subclasses(child)

To inherit from a class, use extends keyword, for example:

class Dog extends Animal {…}

3. Override methods

You can use optional @Override annotation to tell the compiler that the method is supposed to override another method.

If keyword final is used for a method, it cannot be overridden.

4. Calling superclass constructor

Each subclass constructor must implicitly or explicitly call one of its superclass’s constructors to initialize the instance variables inheried from the superclass.

If the subclass constructor did not invoke the superclass’s constructor explicitly, the compiler would attempt to insert a call to the superclass’s default or no-argument constructor.

5. classes and objects

Access modifiers: default, private, protected, public

Access modifiers allow encapsulation, one of the fundamental concepts of OOP.

private           只有同类中能访问

default          同包内能访问

protected      同包内和别的包中的子类能访问

public            都能访问

6.2 Composition

Inheritance —— is-a relationship

Composition —— has-a relationship

Inheritance耦合更紧密(tightly coupled),Composition是松散耦合的(loosely coupled),所以有时用composition更好。

6.3 Polymorphism多态

Polymorphism allows you to define one interface and have multiple implementations.

Compile-time Polymorphism (static polymorphism achieved by method overloading)

Runtime Polymorphism (Dynamic Mehod Dispatch achieved by method overriding)

override重写:不同类中名字相同,参数相同。

overload重载:同一类中名字相同,但参数和行为不同

Chapter 7

7.1 Abstract classes

       An abstract class is a class that does not have concrete implementations for all or some of the methods it desctribes.

       An abstract class cannot be instantiated.

       A class that contains abstract methods must be an abstract class even if that class contains some concrete methods.

       Example of defining an abstract class:

public abstract class Shape 
{
    public abstract double area();
    public abstract double circumference();
}

Abstract class只要有一个abstract method就行,Interface要求所有constants和methods都是abstract的。

7.2 Interface

    An interface decreibes a set of methods that can be implemented in unrealted classes.

  An interface is an agreement between programmer and Java compiler to implement the methods described in the interface.

    An interface declaration begins with the keyword interface and typically contains only constants and abstract methods.

    All interface members must be public.

    Mandatory methods declared in an interface are implicitly public abstract methods.(如果没有显式地使用关键字,这些方法会默认视为public和static)

    All fields are implicitly public, static and final (如果没有显式地指定修饰符,所有字段会被默认为public, static and final)

       An interface cannot be instantiated, so it does not define a constructor.

Using multiple interfaces: 用逗号隔开

public class Subclass extends Superclass implements FirstInterface, SecondInterface{
    //省略内容
}

Example – two interfaces

interface Pianist {
    default void play() {System.out.println("Bling blong"); }
}
interface violinist {
    deault void play() {System.out.println("Viih vooh"); }
}
class Musician implements Pianist, Violinist {
    public void play() {
        Pianist super.play();  // 实现Pianist的play()方法
    }
}
public class InterfaceEampleMusician {
    public static void main(String[] args) {
        new Musician().play();
    }
}

// 运行结果为 Bling blong

Example – extended interfaces

interface Scalable {void scale(double scaler); }
interface Rotatable {void rotate(); }
interface Transformable extends Scalable, Rotatable {}
class Rectangle implements Transformable {
    public double w, h;
    public Rectangle(double w, double h) {this.w = w; this.h = h; }
    public void scale(double scaler) {this.w *= scaler; this.h *= scaler; }
    public void rotate() {double temp = this.w; this.w = this.h ; this.h = temp; }
}
public class InterfaceExampleTransformable {
    public static void main(String[] args) {
    Rectangle rect = new Rectangle(10.0, 5.0);
    rect.scale(0.5);
    System.out.printf("New dimensions: %f, %f\n", rect.w, rect.h);
    }
}

// 运行结果为 New dimensions: 5.000000, 2.500000

Any interface containing only one abstract method is known as a functional interface. Optional annotation  @FunctionalInterface  can be used.

Chapter 8

8.1 Advanced methods and concurrency

  • call stack
  • use keyword "this" to access class attribute
  • recursive method 递归函数

        A recursive method returns a call to itself until a base case is reached.

8.2 Exception handling

Checked exceptions: 运行异常,都是RuntimeException类及其子类异常

Unchecked exceptions: 编译异常,Exception中除了RuntimeException以外的异常

Checked exceptions must be declared by throws keyword.

1. Checked exception example with throws

import java.io.*;
public class ExceptionTest {
    public static void main(String[] args) throws IOException {
        FileInputStream inputStream = null;
        inputStream = new FileInputStream("file.txt");
        int m;
        while ((m = inputStream.read()) != -1) {
            System.out.print((char)m);
        }
        inputStream.close();
    }
}

2. try … catch

try {
    // do something that can cause an exception
}
catch(Exception e) {
    // do this if there was an exception
}
continue the program here normally

The "finally" block is guaranteed to execute whether there is exception or not.

try {
    setAge(age);
    openFile(filename);
}
catch age(IllegalArgumentException e) {
    System.out.println("Unchecked exception!");
    System.err.println(e);
}
catch age(IOException e) {
    System.out.println("Checked exception!");
    System.err.println(e);
}
finally {
    System.out.println("Print this anyways.");
}

8.3 User-defined exceptions

自定义的exception可以用来catch non-programatic problem.

Chapter 9

9.1 Introduction to graphical user interfaces (GUI)

A graphical user interface (GUI) presents a user-friendly mechanism for interacting with an app.

Java GUI uses the GUI components provided by the underlying platform.

GUI libraries for Java: Abstract Window Toolkit (AWT), Swing, JavaFX

Swing uses the common model-view-controller (MVC) design pattern.

Swing is cross-platform.

Swing is extensive.

view: the way that the component looks when rendered on the screen

controller: the way the component reacts to the user

model: the state information associated with the component.

Java foundation classes (JFC) encompass a group of features for building GUIs and adding rich graphics functionality and interactivity to Java applications.

  • In Swing, the GUI is composed of graphical components.

       JFrame: a window or container for GUI

       JLabel: can include static text or an image

       JButton: implements a button that can be pressed

  • Setting frame size

frame.pack()  //自动设置size

用setSize() or setBounds() 可以自己设置

      

9.2 Using top-level containers in Swing

Swing provides two generally useful top-level container classes: JFrame and JDialog

Each program that uses Swing components has at least one top-level container that is the root of a containment hierarchy (容器分层结构).

       To appear on screen, every GUI component must be part of a containment hierarchy.

       Each GUI component can be contained only once. If a component is already in a container and you try to add it to another container, the component will be removed from the first container and then added to the second.

       Each top-level container has a content pane (内容页) that contains the visible components in that top-level container’s GUI. The menu bar is by convention positioned within the top-level container, but outside the content pane.

Each top-level container relies on a reclusive intermediate container called the root pane.

A dialog is an independent sub window (or a pop-up window) carrying notifications apart form the main application window. In Swing, class JDialog is used to instatiate top-level containers for dialogs

9.3 Using layouts an buttons in Swing

Adding JComponents

      Different GUI components are represented by subclasses of JComponent

      GUI components are added to containers by using add() method with the added JComponent subclass object as a parameter

Layout managers

       Several Swing and AWT classes provide layout managers for dynamic allocation of GUI components, according to different specific rules.

FlowLayout can be used on JFrame directly.

GridLayout and BoxLayout require creating JPanel object between JFrame and the components.

Buttons: class JButton

       Swing class JButton can display both text and image

Check boxes: class JCheckBox

       For check boxes in menus use the JCheckBoxMenuItem class

       JCheckbox inherits JAbstractButton.

Radio buttons: class JRadioButton

       For radio buttons in menus use the JRadioButtonMenuItem class

       JRadioButton also inherits from JAbstractButton

Chapter 10

10.1 Event listeners and event handlers

JAVA API provides several event listners that can be used to respond to events fired by swing components.

The proper way to implement event listeners depends on the component.

Chapter 11

11.1 Models in Swing

Models store the state of the component and data.

Some components, such as lists, have multiple models.

       For simple components you would normally interact with the component directly, whereas for more complex components, interacting with models is a better choice

       Models allow the separation of data from the view and controller if the MVC pattern is applied.

     Default models can be extended and thus provide custom functionalities and flexibility in deciding how data is stored and retrieved.

      Models automatically propagate changes to all registered listeners, allowing the view to be updated.

11.2 Using JList and JTable with models

Models for JList

ListModel: stores the information about the data items displayed in the list and the list states.

       ListSelectionModel: manages the selection for list data items.

Models for JTable

       Use the class DeaultTableModel: everything is taken care of for you

       Extend the class AbstractTableModel: you manage the data and invoke the “fire” methods

       Implement the interface TableModel: you manage everything.

11.3 Basics of concurrency(并发) 

  • In concurrent programming, blocks of program code are executed concurrently during overlapping time periods.
  • There are two basic units of execution in concurrent programming:

Processes: each process has a self-contained execution environment.

Threads: each thread exists within a process (every process has at least one thread) and therefore threads share the process’s resources, including memory and open files.

Threads are run using short timeslots in round robin fashion (each thread gets its turn alternatingly), creating illusion of CPU multitasking.

  • 在Java中想要实现多线程,有两种手段,一种是继承Thread类,另一种是实现Runable接口。

Threads can be used by extending class Thread. The code to be executed is implemented in overridden method run(). The thread is started using its method start()

Synchronisation (同步) is one solution to thread interference.

Using keyword "synchronized" will “lock” the method execution and force other threads to wait until the execution completes.

Interrupt()  //不是中断某个线程,而是向线程发送一个中断信号,让线程在无限等待时(如死锁时)能抛出,从而结束线程。当Java线程处于等待状态时,另一个线程可以通过调用interrupt()方法尝试中断它,在这种情况下,会抛出InterruptedException异常

wait() //Obj.wait()与Obj.notify()必须要与synchronized(Obj)一起使用。wait就是说线程在获取对象锁后,主动释放对象锁,同时本线程休眠。直到有其它线程调用对象的notify()唤醒该线程,才能继续获取对象锁,并继续执行。相应的notify()就是对对象锁的唤醒操作。

Thread.sleep()与Object.wait()二者都可以暂停当前线程,释放CPU控制权,主要的区别在于Object.wait()在释放CPU同时,释放了对象锁的控制。

11.4 Concurrency with Swing

Event dispatch threads, where the code for handling events is executed

Worker threads, where time-consuming backgournd tasks are executed

Chapter 12 

12.1 Reading and writing to text files

  • Java considers a file as a stream of characters (text files) or bytes (binary files): data in files is typically written and read sequentially.

1. java.io包

是Java中一个内置的包,专门用于文件读写的一个操作的类

使用时导入 import java.io. *

2. File 类

可以用File类的对象表示一个文件或者目录

当创建了File对象后,可以利用该对象对文件或者目录进行属性修改,不能直接对文件进行读写操作。

File f1 = new File(“../xxx.txt”)   //实例化,用相对路径relative path

f1.createNewFile()  //创建一个新的空文件

f1.mkdir()    //用文件名创建一个空文件夹(父文件夹必须存在)

f1.mkdirs()   //用文件名创建一个空文件夹(父文件夹若不存在则自动创建)

f1.delete()   //删除文件

f1.exists()   //返回文件是否存在(true or false)

f1.getName()   //得到文件名

f1.getPath()   //得到文件相对路径

f1.getAbsolutePath()   //得到文件绝对路径

f1.isDirectory()   //返回f1是否为目录(true or false

f1.length()   //返回文件大小

3. Stream流

流是指一连串流动的数据信号,通过FIFO(先进先出)的方式接收和发送数据。

数据流又分为输入流和输出流

输入输出流又分为字节流和字符流

1)字节流Byte-based streams:以字节为基本单位,在java.io包中,大部分操作继承InputStream类和OutputStream类。

2)字符流Character-based streams:两个字节为基本单位,专门处理字符串和文本,对于字符流进行操作的类主要是Reader类和Writer类。

4. FileWriter的方法write()

用方法close()函数关闭文件或用flush()之后才会真正写入数据。

FileWriter fw = new FileWriter(filename,true); //参数true表示如果已有文件就append内容

fw.write(“Data written in the file”);

fw.close();

5. FileReader类与BuffferedReader类

FileReader提供了read()方法,此方法每次读取指定数量的字符。

更推荐使用BufferedReader class的readLine()方法每次读取一行内容。

FileReader fr = new FileReader(“filename”);

BufferedReader bfr = new BufferedReader(fr);

while((line = bfr.readLine()) != null){

    System.out.println(line);

}

bfr.close();

fr.close();

12.2 Formatted file writing and reading

class Formatter provides similar capability as method System.out.printf

Writing formatted data with Formatter

1) 首先import java.util.Formatter;

2) format() 方法用来生成输出

Formatter fmt = new Formatter(“filename”);

fmt.format(“%s %05d %.2f\n”, name, code, price);

fmt.flush();

3) flush() 方法用来flush数据

4) close() 方法用来关闭formatter

Reading formatted data with Scanner

import java.util.Scanner;

You can use methods nextLine(), next(), nextBoolean(), nextByte(), nextDouble(), nextFloat(), nextInt(), nextLong()


File file = new File(“xxx.txt”);
Scanner scanner =
new Scanner(file);
while(scanner.hasNext()){
    System.out.printf(scanner.next());
}

Reading a CSV file into an array

       CSV(Comma-Separated Values) files contain organized information with items separated by comma delimiters.

Using binary files in Java

       A binary file is considered as a stream of bytes, rather than characters

  • Class FileInputStream can be used to read from binary files

Method read() can be used to read individual bytes or a sequence of bytes into a byte array

继承于InputStream类,这是一个文件输入流,进行文件读操作的最基本的类

由于是字节流,无法读取中文字符。输入流中用byte数组来存储数据,不用考虑数据格式,所以这两种操作的效率比较高

  • Class FileOutputStream can be used to write to binary files

Method write() can be used to write individual bytes or a byte array into the file

  • Both classes are instantiated by using the filename as an argument to the constructor, and closed using method close()

12.3 Serialisation and deserialization

The reverse process, deserialization, is the process of contructing a data structure or an object from a stream of bytes.

  • Java supports native serialization of objects implementing Serializable interface.

The main advantage of native serialization is that it is built-in in Java and does not require any external libraries.

The main disadvantage of native serialization is that it is Java-specific: serialized objects cannot be directly used in other platforms by default.

The serialized class need to implement a constructor without parameters as well as getter and setter methods in standard format the serialized instance variables.

原生序列化不适合跨平台操作。

JSON和XML之类的数据格式通常用作序列化数据的平台独立格式。

In Java, Java Architecture for XML Binding (JAXB) is used to convert Java objects into XML code and XML code into Java objects.

In Java, serialization (marshalling) and deserialization (unmarshalling) are supported via JAXB APIs.

12.4 Functional programming and streams

Functional programming is a programming paradigm especially useful for chaining functions in a stream pipeline. 函数式编程是一种编程范式,特适用于在流水线中链接函数。

In functional programming, functions transform inputs.

Java is not really a functional programming language.

Pure functions are stateless and just transform inputs to outputs.

Chapter 13

13.1 Generics (泛型) in Java

  • In Java, generic reference types parameters can be used instead of specific reference type parameters

Often used to specify the payload (载荷) of a collection.

The use of generics is useful to ensure type safety

Java中泛型标记符

E

Element(在集合中使用,因为集合中存放的是元素)

T

Type(Java类)

K

Key(键)

V

Value(值)

N

Number(数值类型)

?

表示不确定的Java类型

13.2 Queues and sets

Queues:

       Usually, elements in queues are ordered in FIFO (First In, First Out) manner.

Set

       Set is a collection that contains no duplicate elements.

       HashSet是无序的,LinkedHashSet是有序的

HashSet

       Indices in HashSet are computed by the hash function

       Elements are accessed by iterating over the set

TreeSet

       Ideal for handling large quantities of sorted data

       Stores data in a red-black self-balancing binary tree

Maps and sets allow efficient processing of sorted data

13.3 Maps and comparators

Maps

       Map elements consists of pairs of keys (K) and values (V)

       HashMap是无序的,LinkedHashMap有序

HashMap

       Cannot contain duplicate keys (but duplicate values are allowed)

TreeMap

       TreeMap has similar internal structure as TreeSet.

       Can be easily divided in submaps that have specific range of keys

Custom comparators

       To use sorting algorithms for objects of user-defined classes, custom comparator must be implemented for comparing the objects.

  • 15
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值