java6

2.当程序中出现异常时,JVM会依据方法调用顺序依次查找有关的错误处理程序。可使用printStackTrace 和getMessage方法了解异常发生的情况。阅读下面的程序,说明printStackTrace方法和getMessage 方法的输出结果分别是什么?并分析异常的传播过程。

    public class PrintExceptionStack {
        public static void main( String args[] )
        {
             try {
                 method1();
              } catch ( Exception e ) {
                 System.err.println( e.getMessage() + "\n" );
                 e.printStackTrace();
              }
        }
       public static void method1() throws Exception
       {
          method2();
       }
       public static void method2() throws Exception
       {
          method3();
       }
       public static void method3() throws Exception
       {
          throw new Exception( "Exception thrown in method3" );
       }
    }
    try捕获异常catch处理

3.阅读下面程序,分析程序的运行结果,解释产生错误的原因,如果删除的是books集合的最后一个对象,运行的结果又是什么?你能对此作出解释吗?如果在遍历时非要删除集合中的元素,应如何实现?

  import java.util.*;
    public class Test
    {
        public static void main(String[] args) 
        {
            Collection<String> books = new ArrayList<String>();
            books.add("One book");
            books.add("Two book");
            books.add("Three book");
            System.out.println("原始元素之后:"+books);
            Iterator<String> it = books.iterator();
            while(it.hasNext())
            {
                String book = (String)it.next();
                System.out.println(book);
                if (book.equals("One book"))
                {
                    books.remove(book);
                }
            }
            System.out.println("移除元素之后:"+books);
        }
    }
    别用Iterator方法输出就好了,或者用Iterator方法删除。

4.HashSet存储的元素是不可重复的。运行下面的程序,分析为什么存入了相同的学生信息?如果要去掉重复元素,应该如何修改程序。

    import java.util.*;
    class Student {
        String id;  
        String name;
        public Student(String id, String name) {
            this.id = id;
            this.name = name;
        }
        public String toString() {
            return "Student id=" + id + ", name=" + name ;
        }
    }
    public class Test
    {
        public static void main(String[] args) 
        {
            HashSet<Student> set = new HashSet<Student>();
            set.add(new Student("1","Jack"));
            set.add(new Student("2","Rose"));
            set.add(new Student("2","Rose"));
            System.out.println(set);                
        }
    }
    没有重写equal方法和hashcode

代码

1079955-20170504224735164-248225440.png

https://git.oschina.net/shuoge/java6

转载于:https://www.cnblogs.com/haha-23333/p/6810287.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值