JavaExam

Contents.png

Java基本編譯操作

$ javac HelloWorld.java
$ java HelloWorld

類,對象

  • What is a Java class?
    ? A template for a new data type (一種數(shù)據(jù)類型,即對象類型)
      – If you write a class, objects of that class’s type can be constructed and used.
    ? A code module(模塊)
        - Class是面相對象程序設(shè)計中 最基本的程序單元。
      – A module is a unit of program code.
      – Putting code in separate classes separates your program’s functionality.
    ? Arrays in Java
      – Not pointers, like C, but first-class objects 
        – Checked at run-time for safety
      – Covered later
    
  • Object

    Everything is an Object.
    
  • Literals

    - Boolean Literals
    ? There are only two: true 、 false
    
    - Underscores (_) in Numeric Literals
    ? any number of underscore characters (_) can appear anywhere between digits in a numerical literal
      – cannotplaceunderscoresinthefollowingplaces:
      ? At the beginning or end of a number
      ? Adjacent to a decimal point in a floating point literal ? Prior to an F or L suffix
      ? In positions where a string of digits is expected
      
    - Binary Literals
    ? the integral types (byte, short, int, and long) can also be expressed using the binary number system.   – Java SE 7
    ? add the prefix 0b or 0B to the number
    
  • static Method

    ? What if you want a method that can be called for the class, without an object? (“class method”)
        
        class StaticFun {
           static void incr() {       WithStaticData.x++;     }   // 不可被重寫,不能是抽象方法
         }
         StaticFun.incr();
    
  • Annotations

    ? @Override:限定重寫父類
    ? @Deprecated:標(biāo)記已過時
    ? @SuppressWarning:抑制編譯器警告 
    ?......
    
  • Overloading 重載

    - Unique combinations of argument types distinguish overloaded methods
    ? One word, many meanings: overloaded
    
    - Overloading with primitives
    ? if you have a data type that is smaller than the argument in the method, that data type is promoted 
    ? if your argument is bigger than the argument expected by the overloaded method, you must cast to the necessary type by placing the type name inside parentheses.
      – If you don’t do this, the compiler will issue an error message
      – narrowing conversion
    
    - no Overloading on return values
    
    - Default constructors: Takes no Arguments
    ? Compiler automatically creates one for you if you write no constructors
    if you define any constructors (with or without arguments), the compiler will not synthesize(合成) one for you
    
  • The meaning of static

    ? there is no this for that particular method // 不支持this
    ? cannot call non-static methods from inside static methods   // psvm
    ? you can call a static method for the class itself, without any object 類名調(diào)用static方法
    
    if you find yourself using a lot of static methods, you should probably rethink your strategy // 盡可能少地使用static方法
    
  • finalize()

    ? Using finalize() to detect an object that hasn't been properly cleaned up.
    ? finalize() is only useful for obscure memory cleanup that most programmers will never use. // 善后
    

包 Package

? A package is a collection of functionally related 'classes' and 'interfaces' providing access protection and namespace management.    (定義)

? Managing “name spaces”
– Class members are already hidden inside class
– Class names could clash(類名沖突)
– Need completely unique name even over the Internet(名稱唯一)

? Creating unique package names (獨一無二的包名)
– Location on disk encoded into package name
– bruceeckel.com (Note change to lowercase 'com') 
    package com.bruceeckel.util;
    
? Legalizing Package Names  ('域名'與'包名'完全逆序)
    Domain Name → Package Name Prefix
    hyphenated-name.example.org → org.example.hyphenated_name
    example.int → int_.example

? 'import' the constants and static methods
    – do not need to prefix the name of their class (無需重寫包名as前綴)

? “Friendly”  (同一個包內(nèi),任意調(diào)用類方法或類成員)
    - Default access, has no keyword (Also referred to as "package access")
    - public to other members of the same package, private to anyone outside the package
 ? AccessControl
 public: Interface Access
 private: Can’t Touch That!
 protected: deals with inheritance
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

繼承 inheritance

繼承是子類利用父類中定義的方法和變量就像它們屬于子類本身一樣。
方法的覆蓋:在子類中重新定義父類中已有的方法。

通過在類的聲明中加入extends子句來創(chuàng)建一個類的子類. 
如果缺省extends子句,則該類為java.lang.Object的子類。

子類可以繼承父類中訪問權(quán)限設(shè)定為public、 protected、 default的成員變量和方法。
但是不能繼承訪問權(quán)限為private的成員變量和方法。

方法覆蓋(overriding)指子類對 父類的方法進行改寫
子類覆蓋的方法同父類的方法要保持名稱、返回值類型、 參數(shù)列表的統(tǒng)一。
? 改寫后的方法不能比被覆蓋的方法 有更嚴格的訪問權(quán)限
? 改寫后的方法不能比被覆蓋的方法 產(chǎn)生更多的異常
  • Upcasting ("向上"類型轉(zhuǎn)換)

  • The final Keyword

    ? "This cannot be changed"
        
    ? A bit confusing: two reasons for using it 
      – Design
      – Efficiency
    
    ? final data ? 修飾變量,變量就變成了常量;
    ? final methods ? 修飾方法,方法就'不'能再'覆蓋'; 
    ? final class ? 修飾類,類就'不'能再'繼承'.
    
    ? final arguments
      void f(final int i) { // ...
        - Primitives can’t be changed inside method
              void g(final Bob b) {
                    b = new Bob(); (錯 × ) // 不可更改
                }
        - References can’t be rebound inside method
        - Generally, neither one is used
    
  • Pure Inheritance vs. Extension

    -  Pure Inheritance  “Is a” 
      ?Cannot extend the interface (不擴展)
           
    - Extension
      ? Extending the interface (擴展,加入新方法)
    

多態(tài) polymorphism

? Dynamic Binding in Java
binding occurs at run time, based on the type of object. Late binding is also called dynamic binding or run-time binding.
    
    
 * 隱式調(diào)用 super() 時,radius為0  (父類調(diào)用重寫方法,子類成員變量還未初始化)
 * 子類重寫后,new子類對象--調(diào)用子類重寫后的方法
 
     
? 執(zhí)行順序
1. 主函數(shù)所在類中的static字段\代碼塊(而非static 方法),若該類為子類,則先執(zhí)行父類中的static字段,再執(zhí)行該類的static字段
2. main()主函數(shù)
3. new Cat()  
     3.1> 隱含調(diào)用 Animal() 父類構(gòu)造方法 (先加載父類成員\代碼塊(先static后non-static);后加載構(gòu)造函數(shù))
     3.2> 加載 Cat類的成員變量、代碼塊 (先static后non-static)
     3.3> 順序執(zhí)行 Cat() 的構(gòu)造方法  // 構(gòu)造函數(shù)總是類的最后被調(diào)用,類中的方法不加載

抽象類 abstract class

? definition: Java classes that cannot be instantiated! 
  //抽象類不能被實例化,如果被實例化,就會報錯,編譯無法通過。只有抽象類的非抽象子類可以創(chuàng)建對象
? conceptually: a hybrid(混合) of a Java class and interface  

* 一個類只能繼承一個抽象類,而一個類卻可以實現(xiàn)多個接口
  • 抽象方法
- bstract關(guān)鍵字同樣可以用來聲明抽象方法,抽象方法只包含一個方法名,而沒有方法體。
- 抽象方法沒有定義,方法名后面直接跟一個分號,而不是花括號

聲明抽象方法會造成以下兩個結(jié)果:
- 如果一個類包含抽象方法,那么該類'必須是抽象類'
- 任何子類必須重寫父類的抽象方法,或者聲明自身為抽象類

- 抽象類的非抽象子類必須實現(xiàn)抽象類中的抽象方法
  • Summary
1. 抽象類不能被實例化,如果被實例化,就會報錯,編譯無法通過。只有抽象類的非抽象子類可以創(chuàng)建對象。
2. 抽象類中不一定包含抽象方法,但是有抽象方法的類必定是抽象類。
3. 抽象類中的抽象方法只是聲明,不包含方法體,就是不給出方法的具體實現(xiàn)也就是方法的具體功能。
4. 構(gòu)造方法,類方法(用static修飾的方法)不能聲明為抽象方法。 // important
5. 抽象類的子類必須給出抽象類中的抽象方法的具體實現(xiàn),除非該子類也是抽象類。

接口 Interface

- 接口(英文:Interface),在JAVA編程語言中是一個抽象類型,是'抽象方法'的集合,接口通常以interface來聲明。一個類通過實現(xiàn)接口的方式,從而來繼承接口的抽象方法 
    
- 一個實現(xiàn)接口的類,必須實現(xiàn)接口內(nèi)所描述的'所有方法',否則就必須聲明為'抽象類'.

- 接口特性
    - 接口'無法實例化對象'.
    - 接口'沒有構(gòu)造方法'.
    - 接口中所有的方法必須是'抽象方法'.(方法'隱式抽象'為 public abstract,不能在接口中實現(xiàn))
        and default and static methods (需實現(xiàn))
    - 接口'不能包含成員變量',除了 static 和 final 變量.(隱式指定為 public static final members)
    - 接口不是被類繼承了,而是要被類'實現(xiàn)'.
    - 接口支持'多“繼承”'(via 'implements'關(guān)鍵字). (補充:一個接口能繼承另一個接口(使用'extends'關(guān)鍵字))
   
- Using an Interface as a Type
    public static void t(CanFight x) { x.fight(); }     // CanFight is interface

- 接口可以嵌套在類中,也可以嵌套在其他接口中
  • Default Methods (可以被重寫)

  • Static Methods (不可被繼承)

?

?

Generic

class NewPair<S, T> {   // Notice!(class)
        private S first;
        private T second;

        public NewPair(S a, T b) {
            first = a;
            second = b;
        }

        public S getFirst() {
            return first;
        }

        public T getSecond() {
            return second;
        }
    }

------------------------------------------------------------
    public static <T extends Comparable<T>>   
        int countGreaterThan(T[] anArray, T elem) {    //  <T extends Comparable<T>> (method)
        int count = 0;
        for (T e : anArray)
            if (e.compareTo(elem) > 0)      // e.compareTo(elem)
                ++count;
        return count;
    }
------------------------------------------------------------
-  <T extends Comparable<? super T>>

Inner Classes

/** 內(nèi)部類其實嚴重破壞了良好的代碼結(jié)構(gòu),但為什么還要使用內(nèi)部類呢?
因為內(nèi)部類可以隨意使用外部類的成員變量(包括私有)而不用生成外部類的對象,這也是內(nèi)部類的唯一優(yōu)點。
如同心臟可以直接訪問身體的血液,而不是通過醫(yī)生來抽血。**/

Out.In in = new Out().new In(); //class Out{ class In{ } }  // 內(nèi)部類的基本結(jié)構(gòu)
Out.In in = new Out.In();   //class Out{ static class In{ } }   // 靜態(tài)內(nèi)部類
Out out = new Out(); out.outPrint();    // 私有內(nèi)部類
/*class Out{ 
    private class In{ 
        public void print() {
            System.out.println(age);
        } 
    }  
    public void outPrint() {
        new In().print();
    }
}*/
Out out = new Out();  out.Print(3);     // 方法內(nèi)部類
//class Out{ public void Print(final int x) { class In{ } } }

Exception機制

  • Exception 類是 Throwable 類的子類。除了Exception類外,Throwable還有一個子類Error

    異常類有兩個主要的子類:IOException 類和 RuntimeException 類.

img
  • finally關(guān)鍵字

    無論是否發(fā)生異常,finally 代碼塊中的代碼總會被執(zhí)行。
    
    - 在 try/catch 后面添加 finally 塊并非強制性要求的。
    - try 代碼后不能既沒 catch 塊也沒 finally 塊
    
  • try-with-resources

    try-with-resources語句是一個聲明了1到多個資源的try語句。資源是指這個try執(zhí)行完成后必需close掉的對象,比如connection, resultset等。
    
    try-with-resources 語句會確保在try語句結(jié)束時關(guān)閉所有資源。實現(xiàn)了java.lang.AutoCloseable或java.io.Closeable的對象都可以做為資源。
    

    ?

Java數(shù)據(jù)結(jié)構(gòu)

Arrays

// 聲明數(shù)組  - Null reference
double[] myList;         // 首選的方法 
或
double myList[];         //  效果相同,但不是首選方法

// 創(chuàng)建數(shù)組
dataType[] arrayRefVar = new dataType[arraySize];
或
dataType[] arrayRefVar = {value0, value1, ..., valuek};

//Variable Size Array:
     int x[][] = new int[3][];
     x[0] = new int[2];
     x[1] = new int[4];
     x[2] = new int[3];

// wrong example
int table[][]={0,0,0,1,1,1};    (×)
int table[2][3]={0,0,0,1,1,1};  (×)
// Right example
int table[ ][ ]={{0,0,0},{1,1,1}}; (√)

//- Once initialized, the array size is fixed
- Arrays.equals(int[] a, int[] a2): compare two arrays for equality  "比較值相等"
– Arrays.copyOf(int[] original, int newLength): copy specified array
- Arrays.asList((T... a): takes any array and turns it into a List container
- Arrays.fill(int[] a, int val) 
- Arrays.sort(int[] a)
- Arrays.binarySearch(int[] a, int key)     // array must be sorted ; return the index of key

String

- Strings → Numbers
    float a = (Float.valueOf("1")).floatValue();
    float b = Float.parseFloat("1");    // a == b (1.0)
- Numbers → Strings
    String s1 = "" + i;
    String s2 = String.valueOf(i);
    String s3 = Integer.toString(i);
String.equal.png

Collection

img
- Java集合框架為程序員提供了預(yù)先包裝的數(shù)據(jù)結(jié)構(gòu)和算法來操縱他們。
- 集合是一個對象,可容納其他對象的引用。集合接口聲明對每一種類型的集合可以執(zhí)行的操作。
- 集合框架的類和接口均在java.util包中。
- 任何對象加入集合類后,自動轉(zhuǎn)變?yōu)镺bject類型,所以在取出的時候,需要進行強制類型轉(zhuǎn)換。
Container taxonomy - simplified.png
Implementation-style.png
  • 遍歷 ArrayList

    public class Test{
     public static void main(String[] args) {
         List<String> list=new ArrayList<String>();
         list.add("Hello");
         list.add("World");
         list.add("HAHAHAHA");
         //第一種遍歷方法使用foreach遍歷List
         for (String str : list) {  //或 for(inti=0;i<list.size();i++)
            System.out.println(str);
         }
     
         //第二種遍歷,把鏈表 → 數(shù)組相關(guān)的內(nèi)容進行遍歷
         String[] strArray=new String[list.size()];
         list.toArray(strArray);
         for(int i=0;i<strArray.length;i++) //或for(String str:strArray)
         {
            System.out.println(strArray[i]);
         }
         
        //第三種遍歷 使用迭代器iterator進行相關(guān)遍歷
         Iterator<String> ite = list.iterator();
         while(ite.hasNext())//判斷下一個元素之后有值
         {
             System.out.println(ite.next());
         }
     }
    }
    
  • 遍歷 Map

    public class Test{
         public static void main(String[] args) {
          Map<String, String> map = new HashMap<String, String>();
          map.put("1", "value1");
          map.put("2", "value2");
          map.put("3", "value3");
          
          //第一種:普遍使用,二次取值
          System.out.println("通過Map.keySet遍歷key和value:");
          for (String key : map.keySet()) {
           System.out.println("key= "+ key + " and value= " + map.get(key));
          }
          
          //第二種
          System.out.println("通過Map.entrySet使用iterator遍歷key和value:");
          Iterator<Map.Entry<String, String>> it= map.entrySet().iterator();
          while (it.hasNext()) {
           Map.Entry<String, String> entry = it.next();
           System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
          }
          
          //第三種:推薦,尤其是容量大時
          System.out.println("通過Map.entrySet遍歷key和value");
          for (Map.Entry<String, String> entry : map.entrySet()) {
           System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
          }
        
          //第四種
          System.out.println("通過Map.values()遍歷所有的value,但不能遍歷key");
          for (String v : map.values()) {
           System.out.println("value= " + v);
          }
         }
    }
    

    ?

Java IO系統(tǒng)

// InputStreamReader
public static void main(String[] args) {
InputStreamReader isr = new InputStreamReader(System.in); 
    int c;
        try {
            while ((c = isr.read()) != -1)
                System.out.println((char) c);
        } catch(IOException e) {
            //... 
        }
}

// BufferedReader
public static void main(String[] args) { 
    BufferedReader br =
new BufferedReader(new InputStreamReader(System.in)); 
    String s;
    try {
        while ((s = br.readLine()).length() != 0) 
        System.out.println(s);
         } catch(IOException e) {
               //...
        }
}

對象序列化

// Serialization Example - Reading
try {
    InputStream is = new FileInputStream(“file.txt”);
    ObjectInputStream ois = new ObjectInputStream(is);
    ArrayList someList = (ArrayList)ois.readObject();
    is.close();
  } catch (Exception e) { ... }


// Serialization Example - Writing
try {
    OutputStream os = new FileOutputStream(“file.txt”);
    ObjectOutputStream oos = new ObjectOutputStream(os);
    oos.writeObject(someList); 
    oos.flush();
    os.close();
  } catch (IOException ioe) { ... }

NIO

AWT, Swing

public class FrameTester {      //  JFrame Example
            public static void main(String args[]) {
                JFrame f = new JFrame("JFrame Example");
                Container c = f.getContentPane();   
                c.setLayout(new FlowLayout());  // default BorderLayout
                for (int i = 0; i < 5; i++) {
                    c.add(new JButton("No"));
                    c.add(new Button("Batter"));
                }
                c.add(new JLabel("Swing"));
                f.setSize(300, 200);
                f.setVisible(true);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            }
        }
//JOptionPane
class Addition {

    public static void main(String args[]) {

// obtain user input from JOptionPane input dialogs

        String firstNumber =
                JOptionPane.showInputDialog("Enter first integer");

        String secondNumber =
                JOptionPane.showInputDialog("Enter second integer");

        // convert String inputs to int values for use in a calculation
        int number1 = Integer.parseInt(firstNumber);
        int number2 = Integer.parseInt(secondNumber);

        int sum = number1 + number2; // add numbers


        // display result in a JOptionPane message dialog
        JOptionPane.showMessageDialog(null, "The sum is " + sum,
                "Sum of Two Integers", JOptionPane.PLAIN_MESSAGE);
    } // end method main

}

JDBC

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DbUtil {   // conn.createStatement()

    public static final String URL = "jdbc:mysql://localhost:3306/imooc";
    public static final String USER = "liulx";
    public static final String PASSWORD = "123456";

    public static void main(String[] args) throws Exception {
        //1.加載驅(qū)動程序 load database driver class
        Class.forName("com.mysql.jdbc.Driver");
        //2. 獲得數(shù)據(jù)庫連接 connect to database
        Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
        //3.Create a SQL statement object)
        Statement stmt = conn.createStatement();
        // 4. Getting data from a table
        ResultSet rs = stmt.executeQuery("SELECT user_name, age FROM imooc_goddess");
        //5. Use methods of ResultSet (如果有數(shù)據(jù),rs.next()返回true)
        while(rs.next()){
            System.out.println(rs.getString("user_name")+" 年齡:"+rs.getInt("age"));  // rs.getString("user_name") / rs.getInt("age")
        }
    }
}
-------------------------------------------------
public class TestDB {   // conn.preparedStatement(sql)

    public static final String URL = "jdbc:mysql://localhost:3306/imooc";
    public static final String USER = "liulx";
    public static final String PASSWORD = "123456";
    
    public static void main(String[] args) throws Exception {

        //1.加載驅(qū)動程序 load database driver class
        Class.forName("com.mysql.jdbc.Driver");

        //2. 獲得數(shù)據(jù)庫連接 connect to database
        Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);

        //3.Create a SQL statement object)
        PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM TODO");

        // 4. Getting data from a table
        ResultSet resultSet = preparedStatement.executeQuery();

        //5. Use methods of ResultSet (如果有數(shù)據(jù),rs.next()返回true)
        while (resultSet.next()) {
            System.out.println(resultSet.getInt(1));
            System.out.println(resultSet.getString(2));
        }
    }
}

java多線程

class Thread implements Runnable{}
- 實現(xiàn) Runnable 接口來創(chuàng)建線程 
new Thread(Runnable threadOb,String threadName).start;
--------------------------------------
Talker talker = new Talker(); 
Thread t = new Thread(talker); 
t.start();
---
     class Talker implements Runnable {
       public void run() {
         while (true) {
           System.out.println(“Talker”);
            } 
       }
}

--------------------------------------------------------
- 繼承Thread來創(chuàng)建線程
ThreadDemo T1 = new ThreadDemo( );
T1.setName("Thread-1");
T1.start();

void start()
    – Creates a new thread and makes it runnable (包含于Thread,繼承的類亦可重寫)
void run()
    – The new thread begins its life inside this method (繼承的類必須實現(xiàn))
- synchronized methods

class Account {
        private int balance;

        public synchronized void deposit(int val) {
            int newBal;
            newBal = balance + val;
            balance = newBal;
        }

        public void withdraw(int val) {
            synchronized(this) {
            int newBal;
            newBal = balance - val;
            balance = newBal;
            }
        }
    }
Deadlock
- Four Conditions of Deadlock
- Avoiding Deadlock
    - The easiest way to prevent deadlock is to break the fourth condition.
- Wait/Notify Sequence  (均在Object中定義)

1. synchronized(lock){
2.      lock.wait();
9.      consumeResource();
10. }

3. produceResource()
4. synchronized(lock){
5.      lock.notify(); 
6.}

7. Reacquire lock // 重新喚醒鎖
8. Return from wait()
//  ForkJoin Framework
    ForkJoinPool pool = new ForkJoinPool();

    RecursiveTask<List<String>> recursiveTaskInstance = CountByForkJoin.getInstance(list, 5);   // 實例化

    ForkJoinTask<List<String>> future = pool.submit(recursiveTaskInstance);     // 提交可分解的ForkJoinTask任務(wù)

        // do something

    pool.shutdown(); 

java網(wǎng)絡(luò)編程

TCP Socket

protocol localAddr,localPort remoteAddr, remotePort
conn-oriented server ServerSocket() accept()
conn-oriented client Socket()
connectionless server DatagramSocket() receive()
connectionless client DatagramSocket() send()
conn-oriented server
// 1. Create ServerSocket object
ServerSocket serverSocket = new ServerSocket(port);  

// 2. Server listens for client connection  (多于client的步驟)
Socket server = serverSocket.accept();
System.out.println("遠程主機地址:" + server.getRemoteSocketAddress());

// 3. Sending and receiving data    (先read后write)
DataInputStream in = new DataInputStream(server.getInputStream());
DataOutputStream out = new DataOutputStream(server.getOutputStream());

// 4. Server and Client communicate via streams
System.out.println(in.readUTF());   // in.readUTF()
out.writeUTF("謝謝連接我:" + server.getLocalSocketAddress() + "\nGoodbye!");     //out.writeUTF("something")  


// 5. Close streams and connections
server.close();
conn-oriented client
// 1. Create a Socket to connect to server
Socket client = new Socket(serverName, port);   
System.out.println("遠程主機地址:" + client.getRemoteSocketAddress());

// 2. Obtain Socket’s InputStream and Outputstream (先write后read)
OutputStream outToServer = client.getOutputStream();
InputStream inFromServer = client.getInputStream();
DataOutputStream out = new DataOutputStream(outToServer);
DataInputStream in = new DataInputStream(inFromServer);

// 3. Process information communicated
out.writeUTF("Hello from " + client.getLocalSocketAddress());   //out.writeUTF("something")
System.out.println("服務(wù)器響應(yīng): " + in.readUTF()); // in.readUTF()

// 4. Close streams and connection
client.close();

Lambda 表達式

public void printSighting(Sighting record){System.out.println(record.getDetails()); }
等價于                          
(Sighting record) ->
{ System.out.println(record.getDetails()); }      

for(Sighting record : sightings) { printSighting(record);}
等價于
sightings.forEach((Sighting record) ->                               {System.out.println(record.getDetails()); }
 );

? infer type (缺省type)
sightings.forEach((record) ->
    {System.out.println(record.getDetails()); }
);
? single parameter (缺省參數(shù)括號)
sightings.forEach(record ->
    {System.out.println(record.getDetails()); }
);
? single statement (缺省body大括號)
sightings.forEach(record -> System.out.println(record.getDetails()));
? Aggregate Operations 
roster
    .stream()
    .filter(
        p -> p.getGender() == Person.Sex.MALE
            && p.getAge() >= 18
            && p.getAge() <= 25) 
    .map(p -> p.getEmailAddress())
    .forEach(email -> System.out.println(email));

STREAMS

There are three common types of operation:
– Filter: select items from the input stream to pass on to the output stream
– Map: replace items from the input stream with different items in the output stream
– Reduce: collapse the multiple elements of the input stream into a single element
A stream pipeline .png

Summary

  • Summary of Initialization & Cleanup

    ? Initialization is critical for objects, thus Java guarantees it with the constructor
    ? Knowing when to clean up can be difficult in complex systems
    ? Java GC releases memory only: any other cleanup must be done explicitly!
    ? Arrays also have Java-style safety
    

    ?

  • Summary of Hiding the Implementation

    ? Access control tells users what they can & can?t use (shows the area of interest)
    ? Also separates interface & implementation
    ? Allows the class creator to change the implementation later without disturbing client code
    ? An important design & implementation flexibility
    ? Design guideline: always make elements “as private as possible”
    
  • Summary of Reusing Classes

    ? Easy to think that OOP is only about inheritance
    ? Often easier and more flexible to start with composition. Remember to say “has-a” and “is-a”
    ? Use inheritance when it’s clear that a new type is a kind of a base type
    ? ... and especially when you discover a need for polymorphism (next chapter)
    
  • Summary: The Key to OOP

OOP_key.png
  • AbstractClass & Interfaces

    ? abstract類定義方法,實現(xiàn)公共的方法。
    ? 接口(interface)就是'方法聲明'和'常量值'的集合。 
    – An interface defines a protocol of communication between two objects.
    – 從本質(zhì)上講,接口是一種特殊的抽象類,這種抽象類中只包含常量的定義( public static final members)和方法的聲明(public abstract),而沒有變量和方法的實現(xiàn)。
    – (Java 8: default and static methods)
    ? 不相關(guān)的類可以實現(xiàn)(implement)同一個接口, 同一個類可以實現(xiàn)多個不相關(guān)的接口。
    
  • Inner Classes

    ? 允許一個類的定義在另一個類/方法里
    ? 集中使用某些共同特性 → GUI event handlers
    
  • Arrays

    ? An array associates numerical indices to objects – most efficient choice
    ? Arrays in Java are objects which belongs to class Array.
    ? Array objects implements only static arrays
    ? Java follows strict bound checking for referencing array elements.
    ? Array elements can be referenced from 0 to length-1.
    ? Java also follows strict type checking for Array elements.
    ? length is the attribute of each array which can be referenced by arrayreference.length
    
  • Collections Of Objects

    • An array associates numerical indices toobjects

      • A Collection holds single elements, anda Map holds associated pairs

      • Like an array, a List also associates numerical indices to objects

      – Use an ArrayList if you’re doing a lot of random accesses

      – but a LinkedList if you will be doing a lot of insertions and removals in the middle of the list

      • The behavior of queues, deques, and stacks can be provided via the LinkedList

      • A Map is a way to associate not numbers, but objects with other objects

      • HashMap is focused on rapid access

      • TreeMap keeps its keys in sorted order, and thus is not as fast as a HashMap.

      • – A LinkedHashMap keeps its elements in insertion order, but may also reorder them with its LRUalgorithm

      • A Set only accepts one of each type ofobject.

      • HashSets provide maximally fast lookups

      • TreeSets keep the elements in sorted order

      • LinkedHashSets keep elements in insertion order

  • IO

    ? Stream
    – 輸入流只能讀不能寫,輸出流只能寫不能讀;
    – 程序通過輸入流讀入數(shù)據(jù),輸出流寫數(shù)據(jù);
    
    ? I/O is hard
      – deals with real world beyond programmers control 
      – Output easier than input (programmer knows more) 
        – System.out.println() is straightforward
      – Juno Terminal wraps hard to use System.in
    ? java.io package provides lots of useful classes
    ? I/O programs may throw many Exceptions
    ? Even good tools are hard to use when materials are recalcitrant
    ? Count on borrowing from code that works
    
  • NIO

    ? Useful and long awaited addition to Java
    ? New I/O has been widely hailed as an important step forward in getting serious performance out of the Java platform.
    ? Besides raw performance, it provides the most critical I/O and networking functionalities that were absent in earlier versions of Java.
    

    ?

補充:

  • .next()

    • random.nextInt(int bound )

      int x = rd.nextInt(36) + 1;  //  Random rd = new Random(); 
      

      ?

    • iterator

     List<String> list = new ArrayList<>();
            Iterator iterator = list.iterator();
            while (iterator.hasNext())  // hasNext()
                System.out.println(iterator.next());    // next()
    

    ?

    • 數(shù)據(jù)庫resultSet.next()

      while (resultSet.next()) {
                  System.out.println(resultSet.getInt(1));
                  System.out.println(resultSet.getString(2));
              }
      

      ?

  • keyword: 不包含sizeof、status

  • FileOutPutStream

     public static void main(String[] args) {
            try {
                String s = "ABCDE";
                byte b[] = s.getBytes();
                FileOutputStream file = new FileOutputStream("test.txt",true);
                file.write(b);
                file.close();
            }catch (IOException e)
            {
                System.out.println(e.toString());
            }
        }
    

    ?

  • BufferedReader、FileReader、PrintWriter、FileWriter

     public static void main(String[] args)
        {
            File file = new File("./src/Exam/in.txt");
            File file1 = new File("./src/Exam/out.txt");
            System.out.println(file.exists());
            try (BufferedReader br = new BufferedReader(new FileReader(file));    // 
                 PrintWriter pw = new PrintWriter(new FileWriter(file1)))
            {
                int i = 0;
                String line;
                while ((line = br.readLine()) != null)      // br.readLine()
                {
                    pw.println("line " + (++i) + "=" + line);  // pw.println()
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    

    ?

 new ObjectOutputStream(new FileOutputStream(“file.txt”))

DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("something") // 網(wǎng)絡(luò)編程
     
    
DataInputStream in = new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());

 new BufferedReader(new FilerReader(“file.txt”));     
 new BufferedReader(new InputStreamReader(System.in)); 
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容