容器作业

容器作业

一、    填空题

  1. Java集合框架提供了一套性能优良、使用方便的接口和类,包括Collection和Map两大类,它们都位于     java.util         包中
  2. 队列和堆栈有些相似,不同之处在于    队列是先进先出,栈是先进后出  
  3.    链接列表      结构是一种由多个节点组成的线性数据结构,并且每个节点包含有数据以及指向下一个节点的引用。
  4. ____LinkedList__________是一种集合类,它 采用链表作为的存储结构,便于删除和添加元素,但是按照索引查询元素效率低下。
  5.      TreetSet         是一种Collection类型的集合类,其中元素唯一,并采用二叉树作为存储结构,元素按照自然顺序排列。
  6. 如果希望将自定义类Student的多个对象放入集合TreeSet,实现所有元素按照某个属性的自然顺序排列,则需要Student类实现____ Comparable_____接口。
  7. 在Java中   hashSet         集合的访问时间接近稳定,它是一种键值对映射的数据结构。这个数据结构是通过数组来实现的。
  8. 迭代器Iterator为集合而生,专门实现集合遍历,该接口有三个方法,分别是hasNext() 、___next()_________、remove()。

 

二、    选择题

1.

以下选项中关于Java集合的说法错误的是( AC   。(选择二项)

 

 

 

 

A.

List接口和Set接口是Collections接口有两个子接口

 

B.

List接口中存放的元素具有有序,不唯一的特点

 

C.

Set接口中存放的元素具有无序,不唯一的特点

 

D.

Map接口存放的是映射信息,每个元素都是一个键值对

 

2.

如下Java代码,输出的运行结果是(  A  )。(选择一项)

 

public class Test {

         public static void main(String[ ] args) {

                  List<String> list=new ArrayList<String>();

                  list.add("str1");

                  list.add(2, "str2");

                  String s=list.get(1);

                  System.out.println(s);

         }

}

 

 

 

 

A

运行时出现异常

 

B.

正确运行,输出str1

 

C.

正确运行,输出str2

 

D.

编译时出现异常

 

3.

以下Java代码的作用是首先将一个数组的内容存入集合,然后判断集合中是否有指定的元素存在,其中共有(    )处错误。(选择一项)

 

import java.util.List;

public class Test {

         public int getIndexofArray(float[] f){

                  int rtn=-1;

                  float objf=3.4;

                  List list=null;

                  for(int i=0;i<f.size( );i++){

                          list.add(f[i]);

                  }

                  for(int i=0;i<list.size( );i++){

                          float tmp=(float)list.get(i);

                          if(objf==tmp){

                                   rtn=i;

                          }

                  }

                  return rtn;

         }      

}

 

 

 

 

A

0

 

B.

1

 

C.

2

 

D.

3

 

4.

分析如下Java 代码,编译运行后将输出( )。(选择一项)

 

public class Test {

         public Test() {

         }

         static void print(List<Integer> al) {

                  al.add(2);

                  al = new ArrayList<Integer>();

                  al.add(3);

                  al.add(4);

         }

         public static void main(String[] args) {

                  List<Integer> al = new ArrayList<Integer>();

                  al.add(1);

                  print(al);

                  System.out.println(al.get(1));

         }

}

 

 

 

 

A

1

 

B.

2

 

C.

3

 

D.

4

 

5.

Java,下列集合类型可以存储无序、不重复的数据的是(  D  )。(选择一项)

 

 

 

 

A

ArrayList

 

B.

LinkedList

 

C.

TreeSet

 

D.

HashSet

 

6.

以下代码的执行结果是( C   )。(选择一项)

 

Set<String> s=new HashSet<String>();

s.add("abc");

s.add("abc");

s.add("abcd");

s.add("ABC");

System.out.println(s.size());

 

 

 

 

A.

1

 

B.

2

 

C.

3

 

D.

4

 

7.

给定如下Java代码,编译运行的结果是( C   )。(选择一项)

 

public class Test {

         public static void main(String[] args) {

                  Map<String, String> map = new HashMap<String, String>();

                  String s = "code";

                  map.put(s, "1");

                  map.put(s, "2");

                  System.out.println(map.size());

         }

}

 

 

 

 

A

编译时发生错误

 

B.

运行时引发异常

 

C.

正确运行,输出:1

 

D.

正确运行,输出:2

 

8.

下面集合类中属于非线程安全,且结构采用了哈希表的是(  C  。(选择一项)

 

 

 

 

A.

Vector

 

B.

ArrayList

 

C.

HashMap

 

D.

Hashtable

 

9.

 

Java中,LinkedList类与ArrayList类同属于集合框架类,下列( CD   )选项中是LinkedList类有而ArrayList类没有的方法。(选择两项)

 

 

 

 

A

add(Object o)

 

B.

add(int index,Object o)

 

C.

getFirst()

 

D.

removeLast()

       

 

三、    判断题

  1. 数组和集合中的元素可以是任何数据类型,包括基本类型和引用类型。(  F )
  2. Java集合中的Set接口和List接口都是从Collection接口派生出来的。(   T )
  3. Collection 接口存储一组不唯一,有序的对象,它有两个子接口:List和Set。(  F  )
  4. Collection是Java集合顶级接口,其中的元素无序,唯一。Java平台不提供这个接口任何直接的实现。( F   )
  5. List是有序的Collection,使用此接口能够精确的控制每个元素插入的位置。用户能够使用索引来访问List中的无素,这类似于Java的数组。(  T  )
  6. HashSet采用哈希表存储结构,特点是查询速度快,但是其中元素无序排列。(T    )
  7. LinkedHashMap是一种有序的HashMap,查询速度快,便于添加删除操作。(   T )
  8. 基本数据类型的值可以被直接存储在Vector对象中。(F    )
  9. Dictionary建立了关键字和值的映射,只要提供一个关键字,Dictionary就会返回一个相应的值。(T    )
  10. 泛型是JavaSE1.7(1.5)的新特性,泛型的本质是参数化类型,也就是说所操作的数据类型被指定为一个参数。Java语言引入泛型的好处是安全简单。( F   )
  11. Collection是专门操作集合的工具类,提供一系列静态方法实现对各种集合操作。( F   )Collection是接口类型,存放单值的最大接口;
     Collections是操作集合的工具类,就像数组一样,Arrays类是数组工具类。
  12. Iterator接口可以遍历任何Collection接口的实现类,可以从一个Collection中使用iterator( )方法来获取迭代器实例。迭代器取代了Java集合框架中的Enumeration。(  T  )

 

四、    简答题

  1. 集合和数组的比较

    相同点:都是数据的容器,一个在数组或集合中可以储存多个数据。

    不同点:1.元素:数组中的元素只能是相同;集合中的元素是任意的(泛型) 数组中可以存储基本类型和引用类型,集合只能存储引用类型

    2.长度(元素个数):数组是定长的,一旦初始化长度就不可以修改;集合长度可以修改,可以删除元素和添加元素。

  1. 简述List、Set、Collection、Map的区别和联系。
  1. ArrayList和LinkedList的区别和联系。

    ArrayList:底层是可变数组

          特点:一种线性的数据结构,连续存储

                   查询快,增删慢   不同步(效率高,不安全)

        LinkedList:底层是链表结构,可以添加null元素,并且可以添加多个null

          特点:链表:链接列表 ,是一种线性结构,一条线把每个节点串联起来节点的组成

  1. HashSet采用了哈希表作为存储结构,请说明哈希表的特点和实现原理。

    提示:结合Object类的hashCode()和equals()说明其原理

    HashSet:equals返回true,hashCode返回相同的整数;哈希表;存储的数据是无序的。成员可为任意Object子类的对象,但如果覆盖了equals方法,同时注意修改hashCode方法。

    HashMap键成员可为任意Object子类的对象,但如果覆盖了equals方法,同时注意修改hashCode方法。

    特点:访问速度快

       大小不受限制

          按键进行索引,没有重复对象

         用字符串(id:string)检索对象(object)

    基本原理:我们使用一个下标范围比较大的数组来存储元素。可以设计一个函数(哈希函数, 也叫做散列函数),使得每个元素的关键字都与一个函数值(即数组下标)相对应,于是用这个数组单元来存储这个元素;也可以简单的理解为,按照关键字为每一 个元素“分类”,然后将这个元素存储在相应“类”所对应的地方
但是,不能够保证每个元素的关键字与函数值是一一对应的,因此极有可能出现对于不同的元素,却计算出了相同的函数值,这样就产生了“冲突”,换句话说,就是把不同的元素分在了相同的“类”之中。后面我们将看到一种解决“冲突”的简便做法。
总的来说,“直接定址”与“解决冲突”是哈希表的两大特点。

  1. Vector和ArrayList的区别和联系。

          Vector的方法都是同步的,是线程安全的,当元素超过它的初始大小时,Vector会将它的容量翻倍

      ArrayList的方法是不同步的,由于线程的同步必然要影响性能,因此,ArrayList的性能比Vector好。ArrayList只增加50%的大小,这样,ArrayList就有利于节约内存空间。

  1. 请你简述HashMap和Hashtable的区别?

 

 

五、    编码题

    1. 使用List和Map存放多个图书信息,遍历并输出。其中商品属性:编号,名称,单价,出版社;使用商品编号作为Map中的key。
      1.  1 public class Book {
         2     private String ID;
         3     private String name;
         4     private Double price;
         5     private String publish;
         6 
         7     public Book() {
         8         super();
         9         // TODO Auto-generated constructor stub
        10     }
        11 
        12     public Book(String iD, String name, Double price, String publish) {
        13         ID = iD;
        14         this.name = name;
        15         this.price = price;
        16         this.publish = publish;
        17     }
        18 
        19     public String getID() {
        20         return ID;
        21     }
        22 
        23     public String getName() {
        24         return name;
        25     }
        26 
        27     public Double getPrice() {
        28         return price;
        29     }
        30 
        31     public String getPublish() {
        32         return publish;
        33     }
        34 
        35     public void setID(String iD) {
        36         ID = iD;
        37     }
        38 
        39     public void setName(String name) {
        40         this.name = name;
        41     }
        42 
        43     public void setPrice(Double price) {
        44         this.price = price;
        45     }
        46 
        47     public void setPublish(String publish) {
        48         this.publish = publish;
        49     }
        50 
        51     @Override
        52     public String toString() {
        53         return ID+"	"+ name+"	"+price+"	"+publish;
        54     }
        55 
        56 }
        57 import java.util.ArrayList;
        58 import java.util.HashMap;
        59 import java.util.Iterator;
        60 import java.util.List;
        61 import java.util.Map;
        62 
        63 public class Book_test {
        64     public static void main(String[] args) {
        65       Book b1 = new Book("A101", "苦难与辉煌", 100D, "清华大学出版社");
        66       Book b2 = new Book("A102", " 欲血荣光", 50D, "北京大学出版社");
        67       Book b3 = new Book("A103", " 红岩	",75D, "人民出版社");
        68       Book b4 = new Book("A104", " 林海雪原", 45D, "清华大学出版社");
        69       List<Book> l = new ArrayList<>();
        70       l.add(b1);
        71       l.add(b2);
        72       l.add(b3);
        73       l.add(b4);
        74       System.out.println("=============使用List存放多个图书信息,遍历并输出=============");
        75       System.out.println("编号	名称		单价	出版社");
        76       Iterator<Book> it = l.iterator();
        77       while(it.hasNext()){
        78           System.out.println(it.next());
        79       }
        80       
        81       System.out.println("
        =============使用Map存放多个图书信息,遍历并输出=============");
        82       Map<String, Book> m = new HashMap<>();
        83       m.put(b1.getID(),b1);
        84       m.put(b2.getID(),b2);
        85       m.put(b3.getID(),b3);
        86       m.put(b4.getID(),b4);
        87       System.out.println("编号	名称		单价	出版社");
        88       for (Book book : l) {
        89         System.out.println(book);
        90     }
        91       
        92     }
        93 }
      2. 使用HashSet和TreeSet存储多个商品信息,遍历并输出;其中商品属性:编号,名称,单价,出版社;要求向其中添加多个相同的商品,验证集合中元素的唯一性。
      3. 提示:向HashSet中添加自定义类的对象信息,需要重写hashCode和equals( )

                  向TreeSet中添加自定义类的对象信息,需要实现Comparable接口,指定比较规则

          1 public class Products  implements Comparable<Products>{
          2     private String ID;
          3     private String name;
          4     private Double price;
          5     private String pbulish;
          6     public Products() {
          7         super();
          8         // TODO Auto-generated constructor stub
          9     }
         10 
         11     public Products(String iD, String name, Double price, String pbulish) {
         12         ID = iD;
         13         this.name = name;
         14         this.price = price;
         15         this.pbulish = pbulish;
         16     }
         17 
         18     public String getID() {
         19         return ID;
         20     }
         21 
         22     public String getName() {
         23         return name;
         24     }
         25 
         26     public Double getPrice() {
         27         return price;
         28     }
         29 
         30     public String getPbulish() {
         31         return pbulish;
         32     }
         33 
         34     public void setID(String iD) {
         35         ID = iD;
         36     }
         37 
         38     public void setName(String name) {
         39         this.name = name;
         40     }
         41 
         42     public void setPrice(Double price) {
         43         this.price = price;
         44     }
         45 
         46     public void setPbulish(String pbulish) {
         47         this.pbulish = pbulish;
         48     }
         49 
         50     @Override
         51     public int hashCode() {
         52         final int prime = 31;
         53         int result = 1;
         54         result = prime * result + ((ID == null) ? 0 : ID.hashCode());
         55         result = prime * result + ((name == null) ? 0 : name.hashCode());
         56         result = prime * result + ((pbulish == null) ? 0 : pbulish.hashCode());
         57         result = prime * result + ((price == null) ? 0 : price.hashCode());
         58         return result;
         59     }
         60 
         61     @Override
         62     public boolean equals(Object obj) {
         63         if (this == obj)
         64             return true;
         65         if (obj == null)
         66             return false;
         67         if (getClass() != obj.getClass())
         68             return false;
         69         Products other = (Products) obj;
         70         if (ID == null) {
         71             if (other.ID != null)
         72                 return false;
         73         } else if (!ID.equals(other.ID))
         74             return false;
         75         if (name == null) {
         76             if (other.name != null)
         77                 return false;
         78         } else if (!name.equals(other.name))
         79             return false;
         80         if (pbulish == null) {
         81             if (other.pbulish != null)
         82                 return false;
         83         } else if (!pbulish.equals(other.pbulish))
         84             return false;
         85         if (price == null) {
         86             if (other.price != null)
         87                 return false;
         88         } else if (!price.equals(other.price))
         89             return false;
         90         return true;
         91     }
         92 
         93     @Override
         94     public String toString() {
         95         return ""+ID+"	"+name+"	"+price+"	"+pbulish;
         96     }
         97 
         98     @Override
         99     public int compareTo(Products o) {
        100         // TODO Auto-generated method stub
        101         return 1;
        102     }
        103 }
        104 public class Test  {
        105     public static void main(String[] args) {
        106         //使用HashSet存储多个商品信息,遍历并输出;
        107         System.out.println("使用HashSet存储多个商品信息,遍历并输出
        ");
        108         HashSet<Products> hs = new HashSet<>();
        109         hs.add(new Products("101","三国演义",50d,"人民出版社"));
        110         hs.add(new Products("102","水浒传",50d,"人民出版社"));
        111         hs.add(new Products("103","西游记",50d,"人民出版社"));
        112         hs.add(new Products("104","红楼梦",50d,"人民出版社"));
        113         System.out.println("编号	名称	单价	出版社");
        114         for (Products p : hs) {
        115             System.out.println(p);
        116         }
        117         
        118         System.out.println("-----------------------------------");
        119         //使用TreeSet存储多个商品信息,遍历并输出;
        120         System.out.println("使用TreeSet存储多个商品信息,遍历并输出
        ");
        121         TreeSet<Products> tr =new TreeSet<>();
        122         System.out.println("编号	名称	单价	出版社");
        123         tr.add(new Products("101","四书",30d,"人民出版社"));
        124         tr.add(new Products("102","五经",40d,"人民出版社"));
        125         tr.add(new Products("103","大学",35d,"人民出版社"));
        126         tr.add(new Products("104","中庸",25d,"人民出版社"));
        127         for (Products p : tr) {
        128             System.out.println(p.toString());
        129         }
        130     }
        131 
        132 }
        1. 实现List和Map数据的转换。具体要求如下:
           1 public class Student {
           2     private int id;
           3     private String name;
           4     private int age;
           5     private String sex;
           6     public Student() {
           7         super();
           8         // TODO Auto-generated constructor stub
           9     }
          10     public Student(int id, String name, int age, String sex) {
          11         this.id = id;
          12         this.name = name;
          13         this.age = age;
          14         this.sex = sex;
          15     }
          16     public int getId() {
          17         return id;
          18     }
          19     public String getName() {
          20         return name;
          21     }
          22     public int getAge() {
          23         return age;
          24     }
          25     public String getSex() {
          26         return sex;
          27     }
          28     public void setId(int id) {
          29         this.id = id;
          30     }
          31     public void setName(String name) {
          32         this.name = name;
          33     }
          34     public void setAge(int age) {
          35         this.age = age;
          36     }
          37     public void setSex(String sex) {
          38         this.sex = sex;
          39     }
          40     @Override
          41     public String toString() {
          42         return id +"	"+ name+"	" + age+"	" + sex;
          43     }
          44     
          45 }

          功能1:定义方法public void listToMap( ){ }将List中Student元素封装到Map中

          1)       使用构造方法Student(int id,String name,int age,String sex )创建多个学生信息并加入List

          2)       遍历List,输出每个Student信息

          3)       将List中数据放入Map,使用Student的id属性作为key,使用Student对象信息作为value

          4)       遍历Map,输出每个Entry的key和value

          public class Student_test1 {
              public void listToMap(){ 
                  Student s1 = new Student(101,"嬴政",35,"男");
                  Student s2 = new Student(102,"刘彻",28,"男");
                  Student s3 = new Student(103,"刘秀",26,"男");
                  Student s4 = new Student(104,"李世民",59,"男");
                  Student s5 = new Student(105,"朱元璋",65,"男");
                  Student s6 = new Student(105,"武则天",54,"女");
                  //1.创建多个学生信息并加入List
                  System.out.println("--------------List遍历---------------
          ");
                  List<Student> l = new ArrayList<>();
                  l.add(s1);
                  l.add(s2);
                  l.add(s3);
                  l.add(s4);
                  l.add(s5);
                  l.add(s6);
                  //2.遍历List,输出每个Student信息
                  for (Student s : l) {
                      System.out.println(s);
                  }
                  System.out.println("-------------Map遍历------------------
          ");
                  //3.将List中数据放入Map,使用Student的id属性作为key,使用Student对象信息作为value
                  Map<Integer, Student> m = new HashMap<>();
                  //4.遍历Map,输出每个Entry的key和value
                  Iterator<Student> it = l.iterator();
                  while(it.hasNext()){
                      Student s = it.next();
                      m.put(s.getId(), s);
                      System.out.println(s);
                  }
                  
              }
              public static void main(String[] args) {
                  Student_test1 s = new Student_test1();
                  s.listToMap();
              }
          }
          功能2:定义方法public void mapToList( ){ }将Map中Student映射信息封装到List
          1)    创建实体类StudentEntry,可以存储Map中每个Entry的信息
          2)    使用构造方法Student(int id,String name,int age,String sex )创建多个学生信息,并使用Student的id属性作为key,存入Map
          3)    创建List对象,每个元素类型是StudentEntry
          4)    将Map中每个Entry信息放入List对象
          public class Student_test2 {
              public void mapToList(){
                  Student s1 = new Student(101,"嬴政",35,"男");
                  Student s2 = new Student(102,"刘彻",28,"男");
                  Student s3 = new Student(103,"刘秀",26,"男");
                  Student s4 = new Student(104,"李世民",59,"男");
                  Student s5 = new Student(105,"朱元璋",65,"男");
                  Student s6 = new Student(105,"武则天",54,"女");
                  //创建多个学生信息,并使用Student的id属性作为key,存入Map
                  Map<Integer, Student> m =  new HashMap<>();
                  m.put(s1.getId(), s1);
                  m.put(s2.getId(), s2);
                  m.put(s3.getId(), s3);
                  m.put(s4.getId(), s4);
                  m.put(s5.getId(), s5);
                  m.put(s6.getId(), s6);
                  //3.创建List对象,每个元素类型是StudentEntry
                  List<StudentEntry> list = new ArrayList<StudentEntry>();
                  
                  for (Map.Entry<Integer, Student> entry : m.entrySet()) {
                      StudentEntry studentEntry = new StudentEntry();
                      // 将map中的一个映射关系,封装为一个studentEntry对象
                      studentEntry.setKey(entry.getKey());
                      studentEntry.setStu(entry.getValue());
                      // 将studentEntry对象List集合
                      list.add(studentEntry);
                  }
                  //5.遍历Map
                          for (StudentEntry se : list) {
                              System.out.println(se.getKey() + "	" + se.getStu());
                          }
              }
              public static void main(String[] args) {
                  Student_test2 s = new Student_test2();
                  s.mapToList();
              }
          }
          
          
          六、    可选题
          1.    假如有以下email数据“aa@sohu.com,bb@163.com,cc@sina.com,..”现需要把email中的用户部分和邮件地址部分分离,分离后以键值对应的方式放入HashMap?
              public class EmailSplit {
              public static void main(String[] args) {
                  String s = "aa@sohu.com,bb@163.com,cc@sina.com";
                  String[] str= s.split(",");//得到每一个email
                  Map<String,String> m = new HashMap<String, String>();//创建HashMap
                  for (String string : str) {//遍历HashMap
                      String[] split = string.split("@");//分割email存入map
                      m.put(split[0], split[1]);
                  }
                  System.out.println(m);
              }
          }
          2.    由控制台按照固定格式输入学生信息,包括学号,姓名,年龄信息,当输入的内容为exit退出;将输入的学生信息分别封装到一个Student对象中,再将每个Student对象加入到一个集合中,要求集合中的元素按照年龄大小正序排序;最后遍历集合,将集合中学生信息写入到记事本,每个学生数据占单独一行。
          推荐步骤:
          a)    创建Student类,并指定按照年龄正序排列
          b)    通过控制台输入多个不同Student信息。格式规定为:编号#姓名#年龄
          c)    取出字符串中相应信息放入Student对象,并将Student加入到集合中
          d)    遍历集合的过程中将学生的信息输入到记事本
          难点:
          e)    如何指定学生按照年龄正序排列
          f)    如果从字符串“编号#姓名#年龄”中提取学生信息
          g)    放入哪种集合后可以保证学生按照年龄大小正序排列
          h)    如何将集合中学生信息写入记事本,每个学生数据占单独一行
          
          public static void main(String[] args) {
                  Scanner sc= new Scanner(System.in);
                  System.out.println("请输入学生学号:");
                  Integer ID= sc.nextInt();
                  System.out.println("请输入学生姓名:");
                  String name = sc.next();
                  System.out.println("请输入学生年龄:");
                  String age = sc.next();
                  Student_6_2 stu = new Student_6_2(ID, name, age);
                  /*Student_6_2 stu1 = new Student_6_2(101, "张三", "20");
                  Student_6_2 stu2 = new Student_6_2(102, "李四", "52");
                  Student_6_2 stu3 = new Student_6_2(103, "王五", "60");
                  Student_6_2 stu4 = new Student_6_2(104, "赵柳", "30");
                  Student_6_2 stu5 = new Student_6_2(105, "陈浩", "45");*/
                  Set<Student_6_2> s = new HashSet<>();
                  s.add(stu);
                  System.out.println(s);
              }
原文地址:https://www.cnblogs.com/topshark/p/10251971.html