美文网首页19-23年 学习笔记
《 Java 核心技术 》学习笔记

《 Java 核心技术 》学习笔记

作者: Du1in9 | 来源:发表于2020-09-17 18:29 被阅读0次

    一)Java白皮书

    二)基本程序设计结构

    移步:https://www.jianshu.com/p/43f45dd0b22f

    三)对象与类

    • 例1 CalendarTest.java
    import java.time.*;
    
    public class CalendarTest
    {
        public static void main(String[] args)
        {
            LocalDate date = LocalDate.now();//date = 2020-06-17
            int month = date.getMonthValue();//month = 6
            int today = date.getDayOfMonth();//today = 17
            System.out.println();
            System.out.println(date);
            
            date = date.minusDays(today-1);//date = date-16 = 2020-06-01
            System.out.println("Mon Tue Wen Thu Fri Sat Sun");
            while(date.getMonthValue() == month)
            {
                System.out.printf("%3d",date.getDayOfMonth());
                if(date.getDayOfMonth() == today)
                    System.out.print("*");
                else
                    System.out.print(" ");
                date = date.plusDays(1);//date = date+1
                int value = date.getDayOfWeek().getValue();//1 = Monday,...7 = Sunday
                if(value == 1) System.out.println();
            }
            System.out.println();
        }
    }
    
    • 例2 EmployeeTest.java
    import java.time.*;
    
    public class EmployeeTest{
        public static void main(String[]args){
            Employee[] staff=new Employee[3];
            staff[0]=new Employee("Lihua",75000,1989,5,2);
            staff[1]=new Employee("Wanggang",65000,1999,6,2);
            staff[2]=new Employee("Libai",105000,1979,7,29);
            for(Employee e:staff){
                e.raiseSalary(5);
            }
            for(Employee e:staff){
                System.out.println("name:"+e.getName());
                System.out.println("salary:"+e.getSalary());
                System.out.println("hireday:"+e.getHireday()+"\n");
            }
        }
    }
    class Employee{
        private String name;
        private float salary;
        private LocalDate hireday;
        public Employee(String n,float s,int year,int month,int day){
            name=n;
            salary=s;
            hireday=LocalDate.of(year,month,day);
        }
        public String getName(){
            return name;
        }
        public float getSalary(){
            return salary;
        }
        public LocalDate getHireday(){
            return hireday;
        }
        public void raiseSalary(double x){
            salary*=(1+x/100);
        }
    }
    
    • 例3 StaticTest.java
    public class StaticTest{
        public static void main(String[]args){
            Employee[] staff=new Employee[3];
            staff[0]=new Employee("Lihua",75000);
            staff[1]=new Employee("Wanggang",65000);
            staff[2]=new Employee("Libai",105000);
            for(Employee e:staff){
                e.setId();
                System.out.println("name:"+e.getName());
                System.out.println("salary:"+e.getSalary());
                System.out.println("id:"+e.getId());
                System.out.println("next id:"+e.getnextId()+"\n");
            }
        }
    }
    class Employee{
        //静态域nextId
        static private int nextId=1;
        private String name;
        private double salary;
        private int id;
        public Employee(String n,double s){
            name=n;
            salary=s;
        }
        public String getName(){
            return name;
        }
        public double getSalary(){
            return salary;
        }
        public int getId(){
            return id;
        }
        //静态方法
        public static int getnextId(){
            return nextId;
        }
        public void setId(){
            id=nextId;
            nextId++;
        }
        //静态的main方法
        public static void main(String[]args){
            Employee e=new Employee("Xiaoming",50000);
            System.out.println("name:"+e.getName());
            System.out.println("salary:"+e.getSalary());
        }
    }
    // 因为有中文注释,编译命令:>> javac -encoding UTF-8 StaticTest.java
    
    • 例3 ParamTest.java
    public class ParamTest{
        public static void main(String[]args){
            //test1,fail
            double percent=10;
            System.out.println("before percent:"+percent);
            tripleValue(percent);
            System.out.println("after percent:"+percent+"\n");
            //test2,success
            Employee e=new Employee("Lihua",50000);
            System.out.println("before salary:"+e.getSalary());
            tripleSalary(e);
            System.out.println("after salary:"+e.getSalary()+"\n");
            //test3,fail
            Employee a=new Employee("A",50000);
            Employee b=new Employee("B",50000);
            System.out.println("before a:"+a.getName()+"   b:"+b.getName());
            swap(a,b);
            System.out.println("after a:"+a.getName()+"   b:"+b.getName()+"\n");
        }
        public static void tripleValue(double percent){
            percent*=3;
            System.out.println("End percent:"+percent);
        }
        public static void tripleSalary(Employee x){
            x.raiseSalary(200);
            System.out.println("End salary:"+x.getSalary());
        }
        public static void swap(Employee a,Employee b){
            Employee temp=a;
            a=b;
            b=temp;
            System.out.println("End a:"+a.getName()+"   b:"+b.getName());
        }
    }
    class Employee{
        private String name;
        private float salary;
        
        public Employee(String n,float s){
            name=n;
            salary=s;
        }
        public String getName(){
            return name;
        }
        public float getSalary(){
            return salary;
        }
        public void raiseSalary(double x){
            salary*=(1+x/100);
        }
    }
    
    • 例4 ConstructorTest.java
    import java.util.*;
    
    public class ConstructorTest{
        public static void main(String[]args){
            Employee[] staff=new Employee[3];
            staff[0]=new Employee("Harry",40000);
            staff[1]=new Employee(60000);
            staff[2]=new Employee();
            for(Employee e:staff){
                System.out.println("name:"+e.getName());
                System.out.println("salary:"+e.getSalary());
                System.out.println("id:"+e.getId()+"\n");
            }
        }
    }
    class Employee{
        private static int nextId;
        private int id;
        private String name="";
        private double salary;
        //静态初始化块
        static {
            Random generator=new Random();
            nextId=generator.nextInt(10000);//nextId:0~9999
        }
        {
            id=nextId;
            nextId++;
        }
        //对象初始化块
        public Employee(String n,double s){
            name=n;
            salary=s;
        }
        //用this调用另一个构造器
        public Employee(double s){
            this("Employee #"+nextId,s);
        }
        //无参数构造器
        public Employee()
        {  } 
        public String getName(){
            return name;
        }
        public double getSalary(){
            return salary;
        }
        public int getId(){
            return id;
        }
    }
    
    • 例5 PackageTest.java
    import com.du1in9.Employee;
    import static java.lang.System.*;
    
    public class PackageTest{
        public static void main(String[]args){
            Employee e=new Employee("Lihua",50000,1949,10,1);
            e.raiseSalary(5);
            out.println("name:"+e.getName());
            out.println("salary:"+e.getSalary());
            out.println("hireday:"+e.getHireday()+"\n");
        }
    }
    

    com/du1in9/Employee.java

    package com.du1in9;
    import java.time.*;
    
    public class Employee{
        private String name;
        private double salary;
        private LocalDate hireday;
        
        public Employee(String n,double s,int year,int month,int day){
            name=n;
            salary=s;
            hireday=LocalDate.of(year,month,day);
        }
        public String getName(){
            return name;
        }
        public double getSalary(){
            return salary;
        }
        public LocalDate getHireday(){
            return hireday;
        }
        public void raiseSalary(double x){
            salary*=(1+x/100);
        }
    }
    

    四)继承

    • 例1 inheritance/ManagerTest.java
    package inheritance;
    
    
    public class ManagerTest
    {
       public static void main(String[] args)
       {
          Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
          boss.setBonus(5000);
    
          Employee[] staff = new Employee[3];
          staff[0] = boss;
          staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
          staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15);
    
          for (Employee e : staff)
             System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
       }
    }
    

    inheritance/Employee.java

    package inheritance;
    
    import java.time.*;
    
    
    public class Employee
    {
       private String name;
       private double salary;
       private LocalDate hireDay;
    
       public Employee(String name, double salary, int year, int month, int day)
       {
          this.name = name;
          this.salary = salary;
          hireDay = LocalDate.of(year, month, day);
       }
       public String getName()
       {
          return name;
       }
       public double getSalary()
       {
          return salary;
       }
       public LocalDate getHireDay()
       {
          return hireDay;
       }
       public void raiseSalary(double byPercent)
       {
          double raise = salary * byPercent / 100;
          salary += raise;
       }
    }
    

    inheritance/Manager.java

    package inheritance;
    
    
    public class Manager extends Employee
    {
       private double bonus;
       
       public Manager(String name, double salary, int year, int month, int day)
       {
          super(name, salary, year, month, day);
          bonus = 0;
       }
       public double getSalary()
       {
          double baseSalary = super.getSalary();
          return baseSalary + bonus;
       }
       public void setBonus(double b)
       {
          bonus = b;
       }
    }
    
    • 例2 类,超类,子类 ABC/Employee.java
    package ABC;
    import java.time.*;
    
    abstract class Person{
       public abstract String getDescription();
       private String name;
    
       public Person(String n){
          this.name = n;
       }
       public String getName(){
          return name;
       }
    }
    
    class Student extends Person{
       private String major;
       public Student(String n, String m){
          super(n);
          this.major = m;
       }
       public String getDescription(){
          return "a student majoring in " + major;
       }
    }
    
    public class Employee extends Person{
       private double salary;
       private LocalDate hireDay;
    
       public Employee(String n, double s, int y, int m, int d){
          super(n);
          this.salary = s;
          hireDay = LocalDate.of(y, m, d);
       }
       public double getSalary(){
          return salary;
       }
       public LocalDate getHireDay(){
          return hireDay;
       }
       public String getDescription(){
          return String.format("an employee with a salary of $%.2f", salary);
       }
       public void raiseSalary(double p){
          double raise = salary * p/100;
          salary += raise;
       }
    }
    
    class PersonTest{
       public static void main(String[] args){
          Person[] people = new Person[2];
          people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
          people[1] = new Student("Maria Morris", "computer science");
          
          for (Person p : people){
             System.out.println(p.getName() + ", " + p.getDescription());
          }
       }
    }
    
    • 例3 equals/Employee.java
    import java.time.*;
    import java.util.Objects;
    
    public class Employee{
       private String name;
       private double salary;
       private LocalDate hireDay;
       public Employee(String n, double s, int y, int m, int d){
          this.name = n;
          this.salary = s;
          hireDay = LocalDate.of(y, m, d);
       }
       public String getName(){
          return name;
       }
       public double getSalary(){
          return salary;
       }
       public LocalDate getHireDay(){
          return hireDay;
       }
       public void raiseSalary(double p){
          double raise = salary * p/100;
          salary += raise;
       }
       public boolean equals(Object o){
          if (o == this) return true;
          if (o == null) return false;
          if (getClass() != o.getClass()) return false;
          Employee other = (Employee) o;
          return Objects.equals(name, other.name) && salary == other.salary && Objects.equals(hireDay, other.hireDay);
       }
       public int hashCode(){
          return Objects.hash(name, salary, hireDay); 
       }
       public String toString(){
          return getClass().getName() + "[ name = " + name + ", salary = " + salary + ", hireDay = " + hireDay + " ]";
       }
       public static void main(String[] args){
          Employee A1 = new Employee("Alice Adams", 75000, 1987, 12, 15);
          Employee A2 = A1;
          Employee A3 = new Employee("Alice Adams", 75000, 1987, 12, 15);
          Employee bob = new Employee("Bob Brandson", 50000, 1989, 10, 1);
    
          System.out.println("A1 == A2: " + (A1 == A2));
          System.out.println("A1 == A3: " + (A1 == A3));
          System.out.println("A1.equals(A3): " + A1.equals(A3));
          System.out.println("A1.equals(bob): " + A1.equals(bob));
          System.out.println("bob.toString(): " + bob);
    
          Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15);
          Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
          boss.setBonus(5000);
          
          System.out.println("boss.toString(): " + boss);
          System.out.println("carl.equals(boss): " + carl.equals(boss));
          System.out.println("A1.hashCode(): " + A1.hashCode());
          System.out.println("A3.hashCode(): " + A3.hashCode());
          System.out.println("bob.hashCode(): " + bob.hashCode());
          System.out.println("carl.hashCode(): " + carl.hashCode());
       }
    }
    
    class Manager extends Employee{
       private double bonus;
       public Manager(String n, double s, int y, int m, int d){
          super(n, s, y, m, d);
          bonus = 0;
       }
       public double getSalary(){
          double baseSalary = super.getSalary();
          return baseSalary + bonus;
       }
       public void setBonus(double b){
          this.bonus = b;
       }
       public boolean equals(Object o){
          if (!super.equals(o)) return false;
          Manager other = (Manager) o;
          return bonus == other.bonus;
       }
       public int hashCode(){
          return super.hashCode() + 17 * new Double(bonus).hashCode();
       }
       public String toString(){
          return super.toString() + "[ bonus = " + bonus + " ]";
       }
    }
    
    • 例4 arrayList/ArrayListTest.java
    package arrayList;
    import java.time.LocalDate;
    import java.util.ArrayList;
    
    class Employee{
       private String name;
       private double salary;
       private LocalDate hireDay;
       // 构造函数
       public Employee(String n, double s, int y, int m, int d){
          this.name = n;
          this.salary = s;
          hireDay = LocalDate.of(y, m, d);
       }
       // 得到名字
       public String getName(){
          return name;
       }
       // 发薪日期
       public double getSalary(){
          return salary;
       }
       // 雇用日期
       public LocalDate getHireDay(){
          return hireDay;
       }
       // 加薪日期
       public void raiseSalary(double p){
          double raise = salary * p/100;
          salary += raise;
       }
    }
    
    public class ArrayListTest{
       public static void main(String[] args){
          ArrayList<Employee> staff = new ArrayList<>();
          staff.add(new Employee("Carl Cracker", 75000, 1987, 12, 15));
          staff.add(new Employee("Harry Hacker", 50000, 1989, 10, 1));
          staff.add(new Employee("Tony Tester", 40000, 1990, 3, 15));
          // for each 循环
          for (Employee e : staff){
              e.raiseSalary(5);
          }
          for (Employee e : staff){
              System.out.println("name = " + e.getName() + ", salary = " + e.getSalary() + ", hireDay = " + e.getHireDay());
          }
       }
    }
    
    • 例5 enums/EnumTest.java
    package enums;
    import java.util.*;
    
    public class EnumTest{  
       public static void main(String[] args){  
          Scanner in = new Scanner(System.in);
          System.out.print("Enter a size: (small, medium, large, extra_large) ");
          // 将输入字符串转换为大写
          String input = in.next().toUpperCase();
          Size s = Enum.valueOf(Size.class, input);
          // 输出尺寸
          System.out.println("size = " + s);
          // 输出尺寸缩写
          System.out.println("abbreviation = " + s.get());
          if (s == Size.extra_large){ System.out.println("Good job!"); }          
       }
    }
    
    enum Size{
       small("S"), medium("M"), large("L"), extra_large("XL");
       private Size(String a){ this.abbreviation = a; }
       public String get(){ return abbreviation; }
       // abbreviation:缩写
       private String abbreviation;
    }
    
    • 例6 reflection/ReflectionTest.java
    package reflection;
    
    import java.util.*;
    import java.lang.reflect.*;
    
    public class ReflectionTest{
       public static void main(String[] args){
          String name;
          if (args.length > 0) name = args[0];
          else{
             Scanner in = new Scanner(System.in);
             System.out.println("Enter class name (e.g. java.util.Date): ");
             name = in.next();
          }
          try{
             Class cl = Class.forName(name);
             Class supercl = cl.getSuperclass();
             String modifiers = Modifier.toString(cl.getModifiers());
             if (modifiers.length() > 0) System.out.print(modifiers + " ");
             System.out.print("class " + name);
             if (supercl != null && supercl != Object.class) System.out.print(" extends " + supercl.getName());
    
             System.out.print("\n{\n");
             printConstructors(cl);
             System.out.println();
             printMethods(cl);
             System.out.println();
             printFields(cl);
             System.out.println("}");
          }
          catch (ClassNotFoundException e){
             e.printStackTrace();
          }
          System.exit(0);
       }
    
       public static void printConstructors(Class cl){
          Constructor[] constructors = cl.getDeclaredConstructors();
          for (Constructor c : constructors){
             String name = c.getName();
             System.out.print("   ");
             String modifiers = Modifier.toString(c.getModifiers());
             if (modifiers.length() > 0) System.out.print(modifiers + " ");         
             System.out.print(name + "(");
             Class[] paramTypes = c.getParameterTypes();
             for (int j = 0; j < paramTypes.length; j++){
                if (j > 0) System.out.print(", ");
                System.out.print(paramTypes[j].getName());
             }
             System.out.println(");");
          }
       }
    
       public static void printMethods(Class cl){
          Method[] methods = cl.getDeclaredMethods();
          for (Method m : methods){
             Class retType = m.getReturnType();
             String name = m.getName();
             System.out.print("   ");
             String modifiers = Modifier.toString(m.getModifiers());
             if (modifiers.length() > 0) System.out.print(modifiers + " ");         
             System.out.print(retType.getName() + " " + name + "(");
             Class[] paramTypes = m.getParameterTypes();
             for (int j = 0; j < paramTypes.length; j++){
                if (j > 0) System.out.print(", ");
                System.out.print(paramTypes[j].getName());
             }
             System.out.println(");");
          }
       }
    
       public static void printFields(Class cl){
          Field[] fields = cl.getDeclaredFields();
          for (Field f : fields){
             Class type = f.getType();
             String name = f.getName();
             System.out.print("   ");
             String modifiers = Modifier.toString(f.getModifiers());
             if (modifiers.length() > 0) System.out.print(modifiers + " ");         
             System.out.println(type.getName() + " " + name + ";");
          }
       }
    }
    
    • 例7 ObjectAnalyzerTest.java
    import java.lang.reflect.AccessibleObject;
    import java.lang.reflect.Array;
    import java.lang.reflect.Field;
    import java.lang.reflect.Modifier;
    import java.util.ArrayList;
    
    class ObjectAnalyzer{
       private ArrayList<Object> x = new ArrayList<>();
       public String toString(Object o){
          if (o == null) return  "  null ";
          if (x.contains(o)) return  "  ... ";
          x.add(o);
          Class cl = o.getClass();
          if (cl == String.class) return (String) o;
          if (cl.isArray()){
             String r = cl.getComponentType() +  "  []{ ";
             for (int i = 0; i < Array.getLength(o); i++){
                if (i > 0) r +=  "  , ";
                Object y = Array.get(o, i);
                if (cl.getComponentType().isPrimitive()) r += y;
                else r += toString(y);
             }
             return r + "}";
          }
          String r = cl.getName();
          do{
             r += "[";
             Field[] fields = cl.getDeclaredFields();
             AccessibleObject.setAccessible(fields, true);
             for (Field f : fields){
                if (!Modifier.isStatic(f.getModifiers())){
                   if (!r.endsWith("[")) r += ",";
                   r += f.getName() + "=";
                   try{
                      Class t = f.getType();
                      Object y = f.get(o);
                      if (t.isPrimitive()) r += y;
                      else r += toString(y);
                   }
                   catch (Exception e){
                      e.printStackTrace();
                   }
                }
             }
             r += "]";
             cl = cl.getSuperclass();
          }
          while (cl != null);
          return r;
       }
    }
    
    public class ObjectAnalyzerTest{
       public static void main(String[] args){
          ArrayList<Integer> s = new ArrayList<>();
          for (int i = 1; i <= 5; i++)
             s.add(i * i);
          System.out.println(new ObjectAnalyzer().toString(s));
       }
    }
    
    • 例8 CopyOfTest.java
    import java.lang.reflect.*;
    import java.util.*;
    
    public class CopyOfTest{
       public static void main(String[] args){
          int[] a = { 1, 2, 3 };
          a = (int[]) goodCopyOf(a, 10);
          System.out.println(Arrays.toString(a));
    
          String[] b = { "Tom", "Dick", "Harry" };
          b = (String[]) goodCopyOf(b, 10);
          System.out.println(Arrays.toString(b));
    
          System.out.println("The following call will generate an exception.");
          b = (String[]) badCopyOf(b, 10);
       }
    
       public static Object[] badCopyOf(Object[] a, int L){
          Object[] newArray = new Object[L];
          System.arraycopy(a, 0, newArray, 0, Math.min(a.length, L));
          return newArray;
       }
       public static Object goodCopyOf(Object a, int L){  
          Class cl = a.getClass();
          if (!cl.isArray()) return null;
          Class componentType = cl.getComponentType();
          int length = Array.getLength(a);
          Object newArray = Array.newInstance(componentType, L);
          System.arraycopy(a, 0, newArray, 0, Math.min(length, L));
          return newArray;
       }
    }
    
    • 例9 M.java
    import java.lang.reflect.*;
    
    public class M{
       public static void main(String[] args) throws Exception{
          Method square = M.class.getMethod("square", double.class);
          Method sqrt = Math.class.getMethod("sqrt", double.class);
          print(1, 10, 10, square);
          print(1, 10, 10, sqrt);
       }
       public static double square(double x){
          return x * x;
       }
       // f 是 Method 类对象
       public static void print(double A, double B, int n, Method f){
          System.out.println(f);
          double dx = (B - A) / (n - 1);
          for (double x = A; x <= B; x += dx){
             // try catch throw 异常机制
             try{
                // invoke 调用本类的静态方法
                double y = (Double) f.invoke(null, x);
                System.out.printf("%10.4f | %10.4f%n", x, y);
             }
             catch (Exception e){
                e.printStackTrace();
             }
          }
       }
    }
    

    五)接 口,lambda 表达式,内部类

    • 例1 EmployeeSortTest.java
    import java.util.*;
    
    class Employee implements Comparable<Employee>{
       private String name;
       private double salary;
       // 构造函数
       public Employee(String n, double s){
          this.name = n;
          this.salary = s;
       }
       public String getName(){
          return name;
       }
       public double getSalary(){
          return salary;
       }
       // 覆盖 Comparable 中的抽象方法 compareTo(Employee)
       public int compareTo(Employee o){
          return Double.compare(salary, o.salary);
       }
    }
    public class EmployeeSortTest{
       public static void main(String[] args){
          Employee[] e = new Employee[3];
          e[0] = new Employee("Harry Hacker", 35000);
          e[1] = new Employee("Carl Cracker", 75000);
          e[2] = new Employee("Tony Tester", 38000);
          // 工资排序
          Arrays.sort(e);
          for (Employee x : e)
             System.out.println("name = " + x.getName() + ", salary=" + x.getSalary());
       }
    }
    
    • 例2 TimerTest.java
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.Timer; 
    
    public class TimerTest{  
       public static void main(String[] args){  
          ActionListener l = new Time();
          // 第一个参数时间间隔,第二个参数监听器对象    
          Timer t = new Timer(10000, l);
          t.start();
          JOptionPane.showMessageDialog(null, "Quit program?");
          System.exit(0);
       }
    }
    class Time implements ActionListener{  
       public void actionPerformed(ActionEvent event){ 
          System.out.println("Time: " + new Date());
          Toolkit.getDefaultToolkit().beep();
       }
    }
    
    • 例3 CloneTest.java
    import java.util.Date;
    import java.util.GregorianCalendar;
    
    class Employee implements Cloneable{
       private String name;
       private double salary;
       private Date hireDay;
    
       public Employee(String n, double s){
          this.name = n;
          this.salary = s;
          hireDay = new Date();
       }
       public Employee clone() throws CloneNotSupportedException{
          Employee c = (Employee) super.clone();
          c.hireDay = (Date) hireDay.clone();
          return c;
       }
       public void setHireDay(int y, int m, int d){
          Date x = new GregorianCalendar(y, m - 1, d).getTime();
          hireDay.setTime(x.getTime());
       }
       public void raiseSalary(double p){
          double raise = salary * p/100;
          salary += raise;
       }
       //////////////////////////
       public String toString(){
          return "Employee [ name = " + name + " , salary = " + salary + " , hireDay = " + hireDay + " ]";
       }
       //////////////////////////
    }
    public class CloneTest{
       public static void main(String[] args){
          try{
             Employee a = new Employee("John Q. Public", 50000);
             a.setHireDay(2000, 1, 1);
             Employee b = a.clone();
             b.raiseSalary(10);
             b.setHireDay(2002, 12, 31);
             System.out.println("a = " + a);
             System.out.println("b = " + b);
          }
          catch (CloneNotSupportedException e){
             e.printStackTrace();
          }
       }
    }
    
    • 例4 LambdaTest.java
    import java.util.*;
    import javax.swing.*;
    import javax.swing.Timer;
    
    public class LambdaTest{
       public static void main(String[] args){
          String[] p = new String[] { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune" };
          System.out.println(Arrays.toString(p));
          System.out.println("Sorted in order: ");
          Arrays.sort(p);
          System.out.println(Arrays.toString(p));
          System.out.println("Sorted by length: ");
          Arrays.sort(p, (first, second) -> first.length() - second.length());
          System.out.println(Arrays.toString(p));
          // 1000ms = 1s
          Timer t = new Timer(1000, event -> System.out.println("The time is: " + new Date()));
          t.start();   
          JOptionPane.showMessageDialog(null, "Quit program?");
          System.exit(0);         
       }
    }
    
    • 例5 InnerClassTest.java
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.Timer;
    
    public class InnerClassTest{
       public static void main(String[] args){
          Talk c = new Talk(1000, true);
          c.start();
          JOptionPane.showMessageDialog(null, "Quit program ?");
          System.exit(0);
       }
    }
    class Talk{
       private int interval;
       private boolean beep;
       public Talk(int i, boolean b){
          this.interval = i;
          this.beep = b;
       }
       public void start(){
          ActionListener x = new Printer();
          Timer t = new Timer(interval, x);
          t.start();
       }
       public class Printer implements ActionListener{
          public void actionPerformed(ActionEvent event){
             System.out.println("Time: " + new Date());
             if (beep) Toolkit.getDefaultToolkit().beep();
          }
       }
    }
    
    • 例6 AnonymousInnerClassTest.java
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.Timer;
    
    public class AnonymousInnerClassTest{
       public static void main(String[] args){
          Talk c = new Talk();
          c.start(1000, true);
          JOptionPane.showMessageDialog(null, "Quit program ?");
          System.exit(0);
       }
    }
    class Talk{
       public void start(int interval, boolean beep){
          ActionListener l = new ActionListener(){
                public void actionPerformed(ActionEvent event){
                   System.out.println("Time: " + new Date());
                   if (beep) Toolkit.getDefaultToolkit().beep();
                }
             };
          Timer t = new Timer(interval, l);
          t.start();
       }
    }
    
    • 例7 StaticInnerClassTest.java
    public class StaticInnerClassTest{
       public static void main(String[] args){
          double[] d = new double[10];
          for (int i = 0; i < d.length; i++){
              d[i] = 100 * Math.random();
              System.out.println(d[i]);
          }
          Array.Pair p = Array.minmax(d);
          System.out.println("min = " + p.getA());
          System.out.println("max = " + p.getB());
       }
    }
    class Array{
       public static class Pair{
          private double A;
          private double B;
          public Pair(double a, double b){
             A = a; 
             B = b;
          }
          public double getA(){
             return A;
          }
          public double getB(){
             return B;
          }
       }
       public static Pair minmax(double[] V){
          double min = Double.POSITIVE_INFINITY;
          double max = Double.NEGATIVE_INFINITY;
          for (double v : V){
             if (min > v) min = v;
             if (max < v) max = v;
          }
          return new Pair(min, max);
       }
    }
    
    • 例8 ProxyTest.java
    import java.lang.reflect.*;
    import java.util.*;
    
    public class ProxyTest{
       public static void main(String[] y){
          Object[] m = new Object[1000];
          for (int i = 0; i < m.length; i++){
             Integer x = i + 1;
             InvocationHandler h = new Trace(x);
             Object proxy = Proxy.newProxyInstance(null, new Class[] { Comparable.class } , h);
             m[i] = proxy;
          }
          Integer key = new Random().nextInt(m.length) + 1;
          int result = Arrays.binarySearch(m, key);
          if (result >= 0) System.out.println( m[result] );
       }
    }
    class Trace implements InvocationHandler{
       private Object target;
       public Trace(Object t){
          target = t;
       }
       public Object invoke(Object proxy, Method m, Object[] y) throws Throwable{
          System.out.print(target);
          System.out.print("." + m.getName() + "(");
          if (y != null){
             for (int i = 0; i < y.length; i++){
                System.out.print(y[i]);
                if (i < y.length - 1) System.out.print(", ");
             }
          }
          System.out.println(")");
          return m.invoke(target, y);
       }
    }
    

    相关文章

      网友评论

        本文标题:《 Java 核心技术 》学习笔记

        本文链接:https://www.haomeiwen.com/subject/ugpoektx.html