20145216史婧瑶《Java程序设计》第5周学习总结

20145216 《Java程序设计》第5周学习总结

教材学习内容总结

第八章 异常处理

8.1 语法与继承架构

  • Java中所有错误都会被打包为对象,运用try、catch,可以在错误发生时显示友好的错误信息。如:

    import java.util.*;
    
    public class Average2
    {
        public static void main(String[] args)
        {
           try
           {
               Scanner console = new Scanner(System.in);
               double sum = 0;
               int count = 0;
               while (true)
               {
                   int number = console.nextInt();
                   if (number ==0)
                   {
                       break;
                   }
                   sum += number;
                   count++;
               }
               System.out.printf("平均 %.2f%n",sum / count);
           }
           catch (InputMismatchException ex)
           {
               System.out.println("必须输入整数");
           }
        }
    }
    
  • 运用try、catch,还可以在捕捉处理错误之后,尝试恢复程序正常执行流程。如:

    import java.util.*;
    
    public class Average3
    {
        public static void main(String[] args)
        {
            Scanner console = new Scanner(System.in);
            double sum = 0;
            int count = 0;
            while (true)
            {
                try
                {
                    int number = console.nextInt();
                    if (number == 0)
                    {
                        break;
                    }
                    sum += number;
                    count++;
                }
                catch (InputMismatchException ex)
                {
                    System.out.printf("略过非整数输入:%s%n", console.next());
                }
            }
            System.out.printf("平均 %.2f%n", sum / count);
        }
    }
    
  • 如果父类异常对象在子类异常前被捕捉,则catch子类异常对象的区块将永远不会被执行。

  • catch括号中列出的异常不得有继承关系,否则会发生编译错误。

  • 在catch区块进行完部分错误处理之后,可以使用throw(注意不是throws)将异常再抛出。如:

    import java.io.*;
    import java.util.Scanner;
    
    public class FileUtil
    {
        public static String readFile(String name) throws FileNotFoundException
        {
            StringBuilder text = new StringBuilder();
            try
            {
                Scanner console = new Scanner(new FileInputStream(name));
                while (console.hasNext())
                {
                    text.append(console.nextLine())
                    .append('
    ');
                }
            }
           catch (FileNotFoundException ex)
            {
               ex.printStackTrace();
                throw ex;
            }
            return text.toString();
        }
    }
    
  • 如果抛出的是受检异常,表示你认为客户端有能力且应该处理异常,此时必须在方法上使用throws声明;如果抛出的异常是非受检异常,表示你认为客户端调用方法的时机错了,抛出异常是要求客户端修正这个漏洞再来调用方法,此时也就不用throws声明。

  • 如果使用继承时,父类某个方法声明throws某些异常,子类重新定义该方法时可以:

    不声明throws任何异常。
    
    throws父类该方法中声明的某些异常。
    
    throws父类该方法中声明异常的子类。
    

但是不可以:

    throws父类方法中未声明的其他异常。

    throws父类方法中声明异常的父类。
  • 在多重方法调用下,异常发生点可能是在某个方法之中,若想得知异常发生的根源,以及多重方法调用下的堆栈传播,可以利用异常对象自动收集的堆栈追踪来取得相关信息,例如调用异常对象的printStackTrace()。如:

    public class StackTraceDemo1
    {
        public static void main(String[] args)
        {
            try
            {
                c();
            }
            catch (NullPointerException ex)
            {
                ex.printStackTrace();
            }
        }
    
        static void c()
        {
            b();
        }
    
        static void b()
        {
            a();
        }
    
        static String a()
        {
            String text = null;
            return text.toUpperCase();
        }
    }
    
  • 要善用堆栈追踪,前提是程序代码中不可有私吞异常的行为。

  • 在使用throw重抛异常时,异常的追踪堆栈起点,仍是异常的发生根源,而不是重抛异常的地方。如:

    public class StackTraceDemo2
    {
        public static void main(String[] args)
        {
           try
           {
               c();
           }
           catch (NullPointerException ex)
           {
               ex.printStackTrace();
           }
        }
    
        static void c()
        {
            try
            {
               b();
            }
            catch (NullPointerException ex)
            {
                ex.printStackTrace();
                throw ex;
            }
        }
    
        static void b()
        {
            a();
        }
    
        static String a()
        {
            String text = null;
            return text.toUpperCase();
        }
    }
    
  • 程序执行的某个时间点或某个情况下,必然处于或不处于何种状态,这是一种断言。

  • 何时该使用断言?

    断言客户端调用方法前,已经准备好某些前置条件(通常在private方法之中)
    
    断言客户端调用方法后,具有方法承诺的结果。
    
    断言对象某个时间点下的状态。
    
    使用断言取代批注。
    
    断言程序流程中绝对不会执行到的程序代码部分。
    
  • 断言是判定程序中的某个执行点必然是或不是某个状态,所以不能当作像if之类的判断式来使用,assert不应当作程序执行流程的一部分。

  • 若想最后一定要执行关闭资源的动作,try、catch语法可以搭配finally,无论try区块中有无发生异常,若撰写有finally区块,则finally区块一定会被执行。如:

    import java.io.*;
    import java.util.Scanner;
    
    public class FileUtil
    {
        public static String readFile(String name) throws FileNotFoundException
        {
            StringBuilder text = new StringBuilder();
            Scanner console = null;
            try
            {
                console = new Scanner(new FileInputStream(name));
                while (console.hasNext()) 
                {
                    text.append(console.nextLine())
                    .append('
    ');
                }
            } 
            finally 
            {
                if(console != null)
                {
                    console.close();
                }
            } 
            return text.toString();
        }
    }
    
  • 如果程序撰写的流程中先return了,而且也有finally区块,那finally区块会先执行完后,再讲将值返回。如:

    public class FinallyDemo
    {
        public static void main(String[] args)
        {
            System.out.println(test(true));
        }
    
        static int test(boolean flag)
        {
            try
            {
                if(flag)
                {
                    return 1;
                }
            }
            finally
            {
                System.out.println("finally...");
            }
            return 0;
        }
    }
    
  • 尝试关闭资源语法:想要尝试自动关闭资源的对象,是撰写在try之后的括号中,如果无须catch处理任何异常,可以不用撰写,也不用撰写finally自行尝试关闭资源。如:

    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    
    public class FileUtil2
    {
        public static String readFile(String name) throws FileNotFoundException
        {
            StringBuilder text = new StringBuilder();
            try(Scanner console = new Scanner(new FileInputStream(name))) 
            {
                while (console.hasNext()) 
                {
                    text.append(console.nextLine())
                       .append('
    ');
                }
            } 
            return text.toString();
        }
    }
    
  • 尝试关闭资源语法可套用的对象,必须操作java.lang.AutoCloseable接口。如:

    public class AutoClosableDemo
    {
        public static void main(String[] args)
        {
            try(Resource res = new Resource())
            {
                res.doSome();
            } 
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }
    }
    
    class Resource implements AutoCloseable
    {
        void doSome()
        {
            System.out.println("作一些事");
        }
        @Override
        public void close() throws Exception
        {
            System.out.println("資源被關閉");
        }
    }
    
  • 尝试关闭资源语法也可以同时关闭两个以上的对象资源,只要中间以分号分隔。如:

    import static java.lang.System.out;
    
    public class AutoClosableDemo2
    {    
        public static void main(String[] args) 
        {
            try(ResourceSome some = new ResourceSome();
                 ResourceOther other = new ResourceOther())
            {
                some.doSome();
                other.doOther();
            } 
            catch(Exception ex) 
            {
                ex.printStackTrace();
            }
        }
    }
    
    class ResourceSome implements AutoCloseable 
    {
        void doSome() 
        {
            out.println("作一些事");
        }
        @Override
        public void close() throws Exception 
        {
            out.println("資源Some被關閉");
        }
    }
    
    class ResourceOther implements AutoCloseable 
    {
        void doOther() 
        {
            out.println("作其它事");
        }
        @Override
        public void close() throws Exception 
        {
            out.println("資源Other被關閉");
        }
    }
    
  • 在try的括号中,越后面撰写的对象资源会越早被关闭。

第九章 Collection与Map

9.1 使用Collection收集对象

  • 收集对象的行为,像是新增对象的add()方法、移除对象的remove()方法等,都是定义在java.util.Collection中。既然可以收集对象,也要能逐一取得对象,这就是java.lang.Iterable定义的行为,它定义了iterator()方法返回java.lang.Iterable操作对象,可以让你逐一取得收集的对象。

  • 收集对象的共同行为定义在Collection中,然而收集对象会有不同的需求。如果希望收集时记录每个对象的索引顺序,并可依索引取回对象,这样的行为定义在java.util.List接口中。如果希望收集的对象不重复,具有集合的行为,则由java.util.Set定义。如果希望收集对象时以队列方式,收集的对象加入至尾端,取得对象时从前端,则可以使用java.util.Queue。如果希望Queue的两端进行加入、移除等操作,则可以使用java.util.Deque。

  • List是一种Collection,作用是收集对象,并以索引方式保留收集的对象顺序,其操作类之一是java.util.ArrayList。如:

    import java.util.*;
    import static java.lang.System.out;
    
    public class Guest
    {
        public static void main(String[] args)
        {
            List names = new java.util.ArrayList();
            collectNameTo(names);
            out.println("訪客名單:");
            printUpperCase(names); 
        }
    
        static void collectNameTo(List names) 
        {
            Scanner console = new Scanner(System.in);
            while(true)
            {
                out.print("訪客名稱:");
                String name = console.nextLine();
                if(name.equals("quit")) 
                {
                    break;
                }
                names.add(name);
            }
        }
    
        static void printUpperCase(List names)
        {
            for(int i = 0; i < names.size(); i++) 
            {
               String name = (String) names.get(i);
                out.println(name.toUpperCase());
            }        
        }        
    }
    
  • 数组在内存中会是连续的线性空间,根据索引随机存取时速度快,如果操作上有这类需求时,像是排序,就可使用ArrayList,可得到较好的速度表现。

  • LinkedList在操作List接口时,采用了链接(Link)结构。

  • 若收集的对象经常会有变动索引的情况,也许考虑链接方式操作的List会比较好,像是随时会有客户端登录或注销的客户端List,使用LinkedList会有比较好的效率。

  • 在收集过程中若有相同对象,则不再重复收集,如果有这类需求,可以使用Set接口的操作对象。如:

    import java.util.*;
    
    public class WordCount
    {
        public static void main(String[] args) 
        {
            Scanner console = new Scanner(System.in);
    
            System.out.print("請輸入英文:");
            Set words = tokenSet(console.nextLine());
            System.out.printf("不重複單字有 %d 個:%s%n", words.size(), words);
        }
    
        static Set tokenSet(String line)
        {
            String[] tokens = line.split(" ");
            return new HashSet(Arrays.asList(tokens));
        }
    }
    
  • HashSet的操作概念是,在内存中开设空间,每个空间会有个哈希编码。

  • Queue继承自Collection,所以也具有Collection的add()、remove()、element()等方法,然而Queue定义了自己的offer()、poll()与peek()等方法,最主要的差别之一在于:add()、remove()、element()等方法操作失败时会抛出异常,而offer()、poll()与peek()等方法操作失败时会返回特定值。

  • 如果对象有操作Queue,并打算以队列方式使用,且队列长度受限,通常建议使用offer()、poll()与peek()等方法。

  • LinkedList不仅操作了List接口,与操作了Queue的行为,所以可以将LinkedList当作队列来使用。如:

    import java.util.*;
    
    interface Request 
    {
        void execute();
    }
    
    public class RequestQueue
    {        
        public static void main(String[] args)
       {
            Queue requests = new LinkedList();
            offerRequestTo(requests);
            process(requests);
        }
    
        static void offerRequestTo(Queue requests)
        {
            for (int i = 1; i < 6; i++) 
            {
                Request request = new Request()
                {
                    public void execute() 
                    {
                        System.out.printf("處理資料 %f%n", Math.random());
                    }
                };
                requests.offer(request);
            }
        }
    
        static void process(Queue requests) 
        {
            while(requests.peek() != null)
            {
                Request request = (Request) requests.poll();
                request.execute();
            }
        }
    }
    
  • 想对队列的前端与尾端进行操作,在前端加入对象与取出对象,在尾端加入对象与取出对象,Queue的子接口Deque就定义了这类行为。

  • java.util.ArrayDeque操作了Deque接口,可以使用ArrayDeque来操作容量有限的堆栈。

  • 泛型语法:类名称旁有角括号<>,这表示此类支持泛型。实际加入的对象是客户端声明的类型。如:

    import java.util.Arrays;
    
    public class ArrayList<E>
    {
         Object[] elems;
        private int next;
    
       public ArrayList(int capacity)
       {
            elems = new Object[capacity];
       }        
    
       public ArrayList()
       {
            this(16);
       }
    
       public void add(E e)
       {
            if(next == elems.length) 
            {
                elems = Arrays.copyOf(elems, elems.length * 2);
            }
            elems[next++] = e;
       }
    
       public E get(int index)
       {
            return (E) elems[index];
       }
    
       public int size()
       {
            return next;
       }
    }
    
  • 相对于匿名类语法来说,Lambda表达式的语法省略了接口类型与方法名称,->左边是参数列,而右边是方法本体。

  • 在Lambda表达式中使用区块时,如果方法必须有返回值,在区块中就必须使用return。

  • interator()方法提升至新的java.util.Iterable父接口。

  • Collections的sort()方法要求被排序的对象必须操作java.lang.Comparable接口,这个接口有个compareTo()方法必须返回大于0、等于0或小于0的数。

  • Collections的sort()方法有另一个重载版本,可接受java.util.Comparator接口的操作对象,如果使用这个版本,排序方式将根据Comparator的compare()定义来决定。如:

    import java.util.*;
    
    class StringComparator implements Comparator<String> 
    {        
        @Override
        public int compare(String s1, String s2)
        {
            return -s1.compareTo(s2);
        }
    }
    
    public class Sort5
    {
        public static void main(String[] args) 
        {
            List<String> words = Arrays.asList("B", "X", "A", "M", "F", "W", "O");
            Collections.sort(words, new StringComparator());
           System.out.println(words);
       }
    }
    
  • 在java的规范中,与顺序有关的行为,通常要不对象本身是Comparable,要不就是另行指定Comparator对象告知如何排序。

  • 若要根据某个键来取得对应的值,可以事先利用java.util.Map接口的操作对象来建立键值对应数据,之后若要取得值,只要用对应的键就可以迅速取得。常用的Map操作类为java.util.HashMap与java.util.TreeMap,其继承自抽象类java.util.AbstractMap。

  • Map也支持泛型语法,如使用HashMap的范例:如:

    import java.util.*;
    import static java.lang.System.out;
    
    public class Messages 
    {
        public static void main(String[] args) 
        {
            Map<String, String> messages = new HashMap<>();
            messages.put("Justin", "Hello!Justin的訊息!");
            messages.put("Monica", "給Monica的悄悄話!");
            messages.put("Irene", "Irene的可愛貓喵喵叫!");
    
            Scanner console = new Scanner(System.in);
           out.print("取得誰的訊息:");
            String message = messages.get(console.nextLine());
            out.println(message);
            out.println(messages);
        }
    }
    
  • 如果使用TreeMap建立键值对应,则键的部分则会排序,条件是作为键的对象必须操作Comparable接口,或者是在创建TreeMap时指定操作Comparator接口的对象。如:

    import java.util.*;
    
    public class Messages2 
    {
        public static void main(String[] args) 
        {
            Map<String, String> messages = new TreeMap<>(); 
            messages.put("Justin", "Hello!Justin的訊息!");
            messages.put("Monica", "給Monica的悄悄話!");
            messages.put("Irene", "Irene的可愛貓喵喵叫!");
            System.out.println(messages);
        }        
    }
    
  • Properties类继承自Hashtable,HashTable操作了Map接口,Properties自然也有Map的行为。虽然也可以使用put()设定键值对应、get()方法指定键取回值,不过一般常用Properties的setProperty()指定字符串类型的键值,getProperty()指定字符串类型的键,取回字符串类型的值,通常称为属性名称与属性值。

  • 如果想取得Map中所有的键,可以调用Map的keySet()返回Set对象。由于键是不重复的,所以用Set操作返回是理所当然的做法,如果想取得Map中所有的值,则可以使用values()返回Collection对象。如:

    import java.util.*;
    import static java.lang.System.out;
    
    public class MapKeyValue 
    {
        public static void main(String[] args)
        {               
            Map<String, String> map = new HashMap<>();
            map.put("one", "一");
            map.put("two", "二");
            map.put("three", "三");
    
            out.println("顯示鍵");
            map.keySet().forEach(key -> out.println(key));
    
            out.println("顯示值");
            map.values().forEach(key -> out.println(key));
        }
    }
    
  • 如果想同时取得Map的键与值,可以使用entrySet()方法,这会返回一个Set对象,每个元素都是Map.Entry实例。可以调用getKey()取得键,调用getValue()取得值。如:

    import java.util.*;
    
    public class MapKeyValue2
    {
        public static void main(String[] args) 
        {
            Map<String, String> map = new TreeMap<>();
            map.put("one", "一");
            map.put("two", "二");
            map.put("three", "三");
            foreach(map.entrySet());
        }
    
        static void foreach(Iterable<Map.Entry<String, String>> iterable)
        {
            for(Map.Entry<String, String> entry: iterable)
            {
                System.out.printf("(鍵 %s, 值 %s)%n", 
                        entry.getKey(), entry.getValue());
            }
        }
    }
    

教材学习中的问题和解决过程

问题1:

Error与Exception的区别:

解决过程:

通过反复看教材,我总结出了以下区别:

Error与其子类实例代表严重系统错误,如硬件层面错误、JVM错误或内存不足等问题,虽然也可以使用try、catch来
处理Error对象,但并不建议,发生严重系统错误时,Java应用程序本身是无力回复的。

Exception或其子类实例代表程序设计本身的错误,所以通常称错误处理为异常处理(Exception Handling)。

问题2:

Exception与RuntimeException的区别:

解决过程:

教材中对Exception与RuntimeException有所解释,但是我并没有完全理解二者的区别,于是我通过上网查资料,总结出以下区别:

Exception:在程序中必须使用try、catch进行处理。

RuntimeException:可以不使用try、catch进行处理,但是如果有异常产生,则异常将由JVM进行处理。

归纳总结:

异常的继承结构:基类为Throwable,Error和Exception继承Throwable,RuntimeException和IOException
等继承Exception。

Exception或其子对象,但非属于RuntimeException或其子对象,称为受检异常;属于RuntimeException衍生出
来的类实例,称为非受检异常。

代码调试中的问题和解决过程

问题:

书上p233页的代码范例中的“!input.matches("\d*")”是什么意思?

解决过程:

通过看书上对代码的解析,得到如下解释:String 的 matches() 方法中设定了"\d*",这是规则表示式,表示检查字符串中的字符是不是数字,若是则 matches() 会返回true。

其他(感悟、思考等,可选)

本周学习了第八、第九章,给我留下的最深刻的印象就是各种类、接口、方法、行为越来越多,有些还很相似,结果经常分不清楚,看到后面的内容又忘记了前面的知识点,学习时一直前后反复翻教材,后来我就尝试做笔记,将重要的、容易混淆的知识点都记下来,发现这样在回顾知识点时很方便,也很清晰明了。虽然这周学习效率不是很高,但是通过对这两章内容的学习,我体会到勤于做笔记和总结对学习是一个很有效的方法。

托管代码截图:

 学习进度条

 代码行数(新增/累积)博客量(新增/累积)学习时间(新增/累积)重要成长
目标 4500行 30篇 350小时 能将java运用自如 
第一周 150/150 2/2 15/15 学习了与java相关的基础知识 
第二周 200/350 1/3 20/35

学习了java的基本语法 

 第三周  450/800  1/4 25/60 

学习了对象和封装的相关知识 

 第四周 687/ 1487  1/5 30/90 

学习了继承与接口的相关知识 

 第五周 803/2290    1/6    30/120 

学习了异常处理以及Collection与Map的相关知识 

参考资料

原文地址:https://www.cnblogs.com/sjy519/p/5342556.html