集合及泛型自测题
- 格式:docx
- 大小:13.38 KB
- 文档页数:2
1. 什么是Java泛型?Java泛型是一种在编译时提供类型检查的机制,它允许程序员在定义类、接口和方法时使用类型参数。
泛型的主要目的是提高代码的重用性和可读性。
2. 请解释Java泛型中的通配符(?)和问号(?extends T)的含义。
通配符(?)表示未知的类型。
问号(?extends T)表示类型参数是T或T的子类。
例如,List<? extends Number>表示这个列表可以包含Number类及其子类的元素。
3. 请解释Java泛型中的通配符(?)和问号(?super T)的含义。
通配符(?)表示未知的类型。
问号(?super T)表示类型参数是T或T的父类。
例如,List<? super Integer>表示这个列表可以包含Integer类及其父类的元素。
4. 请编写一个使用泛型的示例程序。
```javaimport java.util.ArrayList;import java.util.List;public class GenericExample {public static void main(String[] args) {List<String> stringList = new ArrayList<>();stringList.add("Hello");stringList.add("World");System.out.println(stringList);List<Integer> integerList = new ArrayList<>();integerList.add(1);integerList.add(2);System.out.println(integerList);}}```5. 请解释Java泛型中的限制通配符(<? super T, ? extends U>)的含义。
package entity;//学生类,属性为:姓名、性别、分数、年龄、班级public class Student {private String name;private String gender;private int score;private int age;private String classes;public Student(String name,String gender, int score,Stringclasses) { = name;this.gender = gender;this.score = score;this.classes = classes;}public Student(String name, String gender, int age, int score){ = name;this.gender = gender;this.age = age;this.score = score;}public Student(String name, int score) { = name;this.score = score;}public Student(String name) { = name;}protected String getName() {return name;}protected void setName(String name) { = name;}protected int getAge() {return age;}protected void setAge(int age) {this.age = age;}protected String getGender() {return gender;}protected void setGender(String gender) { this.gender = gender;}protected int getScore() {return score;}protected void setScore(int score) { this.score = score;}protected String getClasses() {return classes;}protected void setClasses(String classes) { this.classes = classes;}}第二题答案源码及运行效果截图:package entity;import java.util.HashMap;import java.util.Scanner;public class Homework2 {public static void main(String[] args) { HashMap<String,Student> students=new HashMap<String,Student>();Scanner input=new Scanner(System.in);Student stu1=new Student("杨过", 95);Student stu2=new Student("小龙女", 99);Student stu3=new Student("张无忌", 88);Student stu4=new Student("赵敏", 90);students.put("杨过", stu1);students.put("小龙女", stu2);students.put("张无忌", stu3);students.put("赵敏", stu4);System.out.println("请输入学生姓名:");String key=input.next();if(students.containsKey(key)){Student stu= students.get(key);System.out.println(stu.getName()+"的成绩是:"+stu.getScore());}System.out.println("----------所有学生的成绩是-----------");for(Object value:students.values()){Student stu=(Student) value;System.out.println(stu.getName()+"的成绩是:"+stu.getScore());}}}第三题答案源码及运行效果截图:package entity;import java.util.*;public class Homework3 {public static void main(String[] args) {List<Student> list1=new ArrayList<Student>();List<Student> list2=new ArrayList<Student>();List<Student> list3=new ArrayList<Student>();Student stu1=new Student("张三");Student stu2=new Student("李四");Student stu3=new Student("王五");Student stu4=new Student("成龙");Student stu5=new Student("李娜");Student stu6=new Student("张杰");Student stu7=new Student("刘德华");Student stu8=new Student("张学友");Student stu9=new Student("刘亦菲");list1.add(stu1);list1.add(stu2);list1.add(stu3);list2.add(stu4);list2.add(stu5);list2.add(stu6);list3.add(stu7);list3.add(stu8);list3.add(stu9);Map<String,List<Student>> map=new HashMap<String,List<Student>>();map.put("三年级一班", list1);map.put("三年级二班", list2);map.put("三年级三班", list3);System.out.println("输入班级名称:");Scanner input=new Scanner(System.in);String banji=input.next();System.out.println(banji+"学生列表:");List<Student> list=map.get(banji);for(Student stu:list){System.out.println(stu.getName());}}}第四题答案源码及运行效果截图:package entity;import java.util.*;import java.util.Scanner;public class Homework4 {public static void main(String[] args) {ArrayList<Student> list1=newArrayList<Student>();ArrayList<Student> list2=newArrayList<Student>();ArrayList<Student> list3=newArrayList<Student>();Student stu1=new Student("张三","男",20,85);Student stu2=new Student("李四","男",22,80);Student stu3=new Student("王五","男",24,88);Student stu4=new Student("成龙","男",26,95);Student stu5=new Student("李娜","女",24,99);Student stu6=new Student("张杰","男",23,88);Student stu7=new Student("刘德华","男",28,99);Student stu8=new Student("张学友","男",27,87);Student stu9=new Student("刘亦菲","女",24,97);list1.add(stu1);list1.add(stu2);list1.add(stu3);list2.add(stu4);list2.add(stu5);list2.add(stu6);list3.add(stu7);list3.add(stu8);list3.add(stu9);Map<String,ArrayList<Student>> map=newHashMap<String,ArrayList<Student>>();map.put("三年级一班", list1);map.put("三年级二班", list2);map.put("三年级三班", list3);System.out.println("输入班级名称:");Scanner input=new Scanner(System.in);String banji=input.next();System.out.println(banji+"学生列表:");ArrayList<Student> list=map.get(banji);for(Student stu:list){System.out.println(stu.getName()+"\t"+stu.getGender()+"\t"+stu.getAge());}}}。
∙使用Hashtable集合对象存储电脑信息∙员工数据输入第一部分练习1:使用Hashtable对象存储数据项问题编写一个电脑信息类:包括电脑的型号、价格和出厂日期。
程序应根据用户输入的型号来显示相应的电脑信息。
要求使用Hashtable对象存储电脑信息,并且按照型号排列输出,可以输入一个型号,程序检查判断集合中是否存在该型号的电脑,如果存在则显示具体信息。
分析指导教师分析解题思路可以创建一个包含电脑型号、价格和出厂日期的类Computer,电脑的详细信息再作为一个元素存在Hashtable集合中排列输出可以通过下面这种方式输出:(1)创建一个基于控制台的C#应用程序,命名为“HashtableExm”。
(2)创建Computer类。
(3)完整的代码如下:(4)通过从菜单中选择“生成”→“生成解决方案”,来生成该解决方案。
(5)通过从菜单中选择“调试”→“开始执行(不调试)”选项来执行此应用程序。
程序运行效果图指导教师检查学生进度练习2:员工数据输入问题在一个公司的员工管理系统中,通常会通过窗体输入员工的信息,包括员工的编号,姓名,部门,工资等情况。
现不使用数据库技术,使用SortedLis t来存储不同员工的信息,并且,录入的员工都显示在一个列表框中,还可以删除列表框中的员工,但是同时要删除SortedList对象中的员工,因此SortedLis t对象中的数据要与类表框的数据同步。
界面要求如图:员工信息输入在左边的文本框中输入数据以后,单击“添加”按钮可以把数据添加到SortedList对象中,同时姓名添加到右边列表框中;在右边的列表框中选择一个姓名信息,单击下方的“删除”按钮,可以把该员工删除,同时,SortedList对象中的员工信息也被删除。
推荐步骤:(1)先创建一个员工类Employee来保存员工属性。
(2)创建一个窗体,对照界面,添加相应的控件及其事件。
(3)窗体类完整的代码如下:(4)生成和执行此应用程序,效果如下图所示:程序运行结果图。
6泛型与集合6.1单项选择题1.可实现有序对象的操作就是?( )A.HashMapB.HashSetC.TreeMapD.Stack2.不就是迭代器接口(Iterator)所定义的方法就是( )。
A.hasNext()B.next()C.remove()D.nextElement()3.下面说法不正确的就是( )A.列表(List)、集合(Set)与映射(Map)都就是java、util包中的接口。
B.List接口就是可以包含重复元素的有序集合。
C.Set接口就是不包含重复元素的集合。
D.Map接口将键映射到值,键可以重复,但每个键最多只能映射一个值。
4.下面那些方法不就是接口Collection中已声明的方法( )A.添加元素的add(Object obj) 方法B.删除元素的remove(Object obj)方法C.得到元素个数的length()方法D.返回迭代器的iterator()方法,迭代器用于元素遍历5、下列关于容器的描述中,错误的就是( )A.容器就是由若干个组建与容器组成的B.容器就是对图形界面中界面元素的一种管理C.容器就是一种对指定宽与高的矩形范围D.容器都就是可以独立的窗口6、下列界面元素中,不就是容器的就是( )A、ListB、JFrameC、JDialogD、Panel7、应用程序的main方法中有以下语句,则输出的结果就是( )。
Hashtable hashtable=new Hashtable();hashtable、put("100","aaa");hashtable、put("200","bbb");hashtable、put("300","ccc");System、out、println(hashtable、get("300")、toString()+ hashtable、get("200")、toString()+ hashtable、get("100")、toString());A) aaa B) bbb C) ccc D) cccbbbaaa6.2判断题1.Map接口就是自Collection接口继承而来。
题目:深度探讨Java的泛型与集合编程题一、引言Java作为一种广泛使用的编程语言,其泛型与集合是非常重要的特性。
在编写Java程序时,对泛型与集合的理解和应用至关重要。
本文将深入探讨Java的泛型与集合编程题,帮助读者更深入地理解这一主题。
二、泛型的基本概念和用法1. 什么是泛型?泛型是Java语言中一种重要的特性,它允许我们在编写代码时使用参数化类型,从而提高代码的重用性和安全性。
通过泛型,我们可以在编译时检查类型安全,避免在运行时出现类型转换错误。
2. 泛型的基本用法在Java中,我们可以使用泛型来定义类、接口和方法。
定义一个泛型类可以使用以下语法:```javapublic class Box<T> {private T value;public void setValue(T value) {this.value = value;}public T getValue() {return value;}}```在上面的代码中,Box<T>就是一个泛型类,其中的T表示类型参数。
通过使用泛型,我们可以创建具有不同数据类型的Box对象,从而实现通用性和灵活性。
三、集合框架的基本概念和用法1. 什么是集合框架?集合框架是Java中用来存储和操作数据的一组接口和类。
它提供了一系列的数据结构(如List、Set、Map等)和算法。
在Java中,集合框架是非常常用的,我们几乎可以在所有的Java程序中看到它的身影。
2. 集合框架的基本用法我们可以使用集合框架来存储和操作数据。
可以使用List接口来存储一组有序的数据,使用Set接口来存储一组不重复的数据,使用Map接口来存储键值对等。
通过对集合框架的灵活运用,我们能够更加高效地处理数据。
四、深入理解泛型与集合的编程题1. 编程题1:使用泛型实现一个通用的栈要求:实现一个通用的栈类,能够存储任意类型的数据,并实现入栈、出栈等操作。
java第十九章泛型复习题答案Java泛型复习题答案1. 泛型是什么?泛型是Java语言中的一种特性,它允许在编译时对数据类型进行参数化,从而提高代码的复用性、安全性和可读性。
泛型使得集合类可以存储任意类型的数据,同时保证类型安全。
2. Java泛型中的类型参数有哪些限制?类型参数可以是类、接口或者类型变量。
但是,它们不能是基本数据类型(如int、double等),也不能是数组类型或者具体类(如String、Integer等)。
3. 泛型类和非泛型类的区别是什么?泛型类在声明时指定了类型参数,这使得它能够接受任意类型的数据。
而非泛型类则没有类型参数,它只能接受特定类型的数据。
泛型类提高了代码的复用性,因为同一个类可以用于不同的数据类型。
4. 如何定义一个泛型接口?定义泛型接口时,需要在接口名称后添加类型参数,格式为`<类型参数>`。
例如:```javapublic interface List<E> {void add(E e);E get(int index);}```5. 泛型方法是什么?泛型方法是在方法声明中指定类型参数的方法。
这允许方法接受任意类型的参数,并返回相应类型的结果。
泛型方法的类型参数只在方法级别有效。
6. 如何使用泛型方法?使用泛型方法时,需要在方法调用时指定实际的类型参数。
例如: ```javapublic static <T> void printArray(T[] array) {for (T item : array) {System.out.print(item + " ");}System.out.println();}```7. 为什么说泛型提高了代码的安全性?泛型通过在编译时检查类型,避免了类型转换的错误,从而提高了代码的安全性。
它减少了运行时类型转换异常的可能性,使得代码更加健壮。
8. 如何实现泛型的协变和逆变?协变和逆变是泛型类型参数的子类型关系。
Java集合面试问题40个「附答案」每种编程语言中都有集合,最初的Java版本包含几种集合类:Vector、Stack、HashTable和Array。
随着集合的广泛使用,Java1.2提出了囊括所有集合接口、实现和算法的集合框架。
在保证线程平安的情况下使用泛型和并发集合类,Java已经经历了很久。
它还包括在Java并发包中,阻塞接口以及它们的实现。
集合框架的部分优点如下:(1)使用核心集合类降低开发本钱,而非实现我们自己的集合类。
(2)随着使用经过严格测试的集合框架类,代码质量会得到提高。
(3)通过使用JDK附带的集合类,可以降低代码维护本钱。
(4)复用性和可操作性。
Java1.5引入了泛型,所有的集合接口和实现都大量地使用它。
泛型允许我们为集合提供一个可以容纳的对象类型,因此,如果你添加其它类型的任何元素,它会在编译时报错。
这防止了在运行时出现ClassCastException,因为你将会在编译时得到报错信息。
泛型也使得代码整洁,我们不需要使用显式转换和instanceOf 操作符。
它也给运行时带来好处,因为不会产生类型检查的字节码指令。
Collection为集合层级的根接口。
一个集合代表一组对象,这些对象即为它的元素。
Java平台不提供这个接口任何直接的实现。
Set是一个不能包含重复元素的集合。
这个接口对数学集合抽象进展建模,被用来代表集合,就如一副牌。
List是一个有序集合,可以包含重复元素。
你可以通过它的索引来访问任何元素。
List更像长度动态变换的数组。
Map是一个将key映射到value的对象.一个Map不能包含重复的key:每个key最多只能映射一个value。
一些其它的接口有Queue、Dequeue、SortedSet、SortedMap和ListIterator。
Collection接口指定一组对象,对象即为它的元素。
如何维护这些元素由Collection的详细实现决定。
集合测试题及答案一、单项选择题(每题2分,共10分)1. 集合A={1,2,3},集合B={2,3,4},则A∩B=()A. {1,2,3}B. {2,3}C. {1,4}D. {3,4}2. 集合A={1,2,3},集合B={2,3,4},则A∪B=()A. {1,2,3}B. {2,3}C. {1,2,3,4}D. {3,4}3. 集合A={1,2,3},集合B={2,3,4},则A⊆B是否成立?()A. 成立B. 不成立4. 集合A={1,2,3},集合B={2,3,4},则A⊂B是否成立?()A. 成立B. 不成立5. 集合A={1,2,3},集合B={2,3,4},则A∩B的元素个数为()A. 1B. 2C. 3D. 4二、填空题(每题2分,共10分)6. 若集合A={x|x是4的倍数},集合B={x|x是6的倍数},则A∩B=_________。
7. 集合A={1,3,5},B={2,4,6},则A∪B=_________。
8. 集合A={x|x^2-5x+6=0},解方程得A=_________。
9. 集合A={1,2,3},B={4,5,6},则A∩B=_________。
10. 集合A={x|x是小于10的正整数},则A的元素个数为_________。
三、解答题(每题10分,共20分)11. 已知集合A={1,2,3},B={3,4,5},求A∩B和A∪B,并说明理由。
12. 集合A={x|-2<x<5},B={x|x>3或x<0},求A∩B,并说明理由。
答案:一、单项选择题1. B2. C3. B4. B5. B二、填空题6. {x|x是12的倍数}7. {1,2,3,4,5,6}8. {2,3}9. ∅10. 9三、解答题11. A∩B={3},因为3是集合A和B的共同元素;A∪B={1,2,3,4,5},因为这些元素属于集合A或集合B。
12. A∩B={x|-2<x<0或3<x<5},因为这些元素同时满足集合A和B的条件。
第11章泛型和集合习题解析1.选择题(1)下列方法中,不能用于删除Collection集合中元素的是()。
A、clear()B、isEmpty()C、remove()D、removeAll()答案:B(2)阅读下列的程序import java.util.*;class Student {String name;String age;public Student(String name, String age) { = name;this.age = age;}public String toString() {return name + ":" + age;}}public class Example{public static void main(String[] args) {Set set = new HashSet();set.add(new Student("Tom", "10"));set.add(new Student("Jerry", "10"));set.add(new Student("Tom", "10"));}}下列选项中,程序的运行结果是()。
A、2B、3C、1D、不固定个数答案:B(3)下面关于List集合的描述中,哪一个是错误的?()A、List集合是有索引的B、List集合可以存储重复的元素C、List集合存和取的顺序一致D、List集合没有索引答案:D(4)下列选项中,不属于Map接口的方法的是()。
A、remove(Object key)B、isEmpty( )C、toArray( )D、size( )答案:C(5)要想集合中保存的元素没有重复并且按照一定的顺序排列,可以使用以下哪个集合?()A、LinkedListB、ArrayListC、hashSetD、TreeSet答案:D(6)下面哪个对象不能直接获取java.util.Iterator迭代器进行迭代()。
java 集合练习题Java集合是Java编程语言中非常重要的一部分,它提供了一系列的数据结构和算法,用于存储和操作数据。
在日常的Java开发中,我们经常会遇到各种集合相关的问题和练习题。
本文将通过一些具体的练习题,帮助读者更好地理解和运用Java集合。
1. 题目一:给定一个整数数组,如何去除其中的重复元素并保持原有顺序?解析:我们可以通过使用Set集合来去除重复元素,因为Set集合不允许重复元素的存在。
但是Set集合并不能保持原有的顺序,所以我们可以使用LinkedHashSet来保持元素的插入顺序。
具体实现代码如下:```javaint[] nums = {1, 2, 3, 2, 4, 1, 5};Set<Integer> set = new LinkedHashSet<>();for (int num : nums) {set.add(num);}int[] result = new int[set.size()];int index = 0;for (int num : set) {result[index++] = num;}System.out.println(Arrays.toString(result));```2. 题目二:给定两个整数数组,如何找到它们的交集?解析:我们可以使用Set集合来解决这个问题,先将一个数组中的元素全部添加到Set集合中,然后遍历另一个数组,判断元素是否在Set集合中存在。
具体实现代码如下:```javaint[] nums1 = {1, 2, 2, 1};int[] nums2 = {2, 2};Set<Integer> set = new HashSet<>();for (int num : nums1) {set.add(num);}List<Integer> intersection = new ArrayList<>();for (int num : nums2) {if (set.contains(num)) {intersection.add(num);set.remove(num);}}System.out.println(intersection);```3. 题目三:给定一个字符串,如何统计每个字符出现的次数?解析:我们可以使用Map集合来解决这个问题,遍历字符串的每个字符,将字符作为键,出现的次数作为值,存储到Map集合中。
Module 7-集合和泛型一、选择题:Question 1Given:11. public class Person {12. private name;13. public Person(String name) {14. = name;15. }16. public int hashCode() {17. return 420;18. }19. }Which is true?A. The time to find the value from HashMap with a Person key dependson the size of the map.B. Deleting a Person key from a HashMap will delete all map entries forall keys of type Person.C. Inserting a second Person object into a HashSet will cause the firstPerson object to be removed as a duplicate.D. The time to determine whether a Person object is contained in aHashSet is constant and does NOT depend on the size of the map. Answer: AQuestion 2Given:11. public static Collection get() {12. Collection sorted = new LinkedList();13. sorted.add("B"); sorted.add("C"); sorted.add("A");14. return sorted;15. }16. public static void main(String[] args) {17. for (Object obj: get()) {18. System.out.print(obj + ", ");19. }20. }What is the result?A. A, B, C,B. B, C, A,C. Compilation fails.D. The code runs with no output.E. An exception is thrown at runtime.Answer: BQuestion 3Given:1. import java.util.*;2. public class Example {3. public static void main(String[] args) {4. // insert code here5. set.add(new integer(2));6. set.add(new integer(l));7. System.out.println(set);8. }9. }Which code, inserted at line 4, guarantees that this program willoutput [1, 2]?A. Set set = new TreeSet();B. Set set = new HashSet();C. Set set = new SortedSet();D. List set = new SortedList();E. Set set = new LinkedHashSet();Answer: AQuestion 4Given:1. import java.util.*;2. public class PQ {3. public static void main(String[] args) {4. PriorityQueue<String> pq = new PriorityQueue<String>();5. pq.add("carrot");6. pq.add("apple");7. pq.add("banana");8. System.out.println(pq.poll() +":" + pq.peek());9. }10. }What is the result?A. apple:appleB. carrot:appleC. apple:bananaD. banana:appleE. carrot:carrotF. carrot:bananaAnswer: CQuestion 5Given:1. import java.util.*;2. public class WrappedString {3. private String s;4. public WrappedString(String s) { this.s = s; }5. public static void main(String[] args) {6. HashSet<Object> hs = new HashSet<Object>();7. WrappedString ws1 = new WrappedString("aardvark");8. WrappedString ws2 = new WrappedString("aardvark");9. String s1 = new String("aardvark");10. String s2 = new String("aardvark");11. hs.add(ws1); hs.add(ws2); hs.add(s1); hs.add(s2);12. System.out.println(hs.size()); } }What is the result?A. 0B. 1C. 2D. 3E. 4F. Compilation fails.G. An exception is thrown at runtime.Answer: DQuestion 6Click the Exhibit button.1. import java.util.*;2. public class TestSet {3. enum Example { ONE, TWO, THREE }4. public static void main(String[] args) {5. Collection coll = new ArrayList();6. coll.add(Example.THREE);7. coll.add(Example.THREE);8. coll.add(Example.THREE);9. coll.add(Example.TWO);10. coll.add(Example.TWO);11. coll.add(Example.ONE);12. Set set = new HashSet(coll);13. }14. }Which statement is true about the set variable on line 12? A. The set variable contains all six elements from the coll collection,and the order is guaranteed to be preserved.B. The set variable contains only three elements from the coll collection, and the order is guaranteed to be preserved.C. The set variable contains all six elements from the coil collection,but the order is NOT guaranteed to be preserved.D. The set variable contains only three elements from the coil collection, but the order is NOT guaranteed to be preserved. Answer: DA programmer has an algorithm that requires a java.util.List thatprovides an efficient implementation of add(0,object), but does NOT need to support quick random access. What supports these requirements?A. java.util.QueueB. java.util.ArrayListC. java.util.LinearListD. java.util.LinkedListAnswer: DQuestion 8Click the Exhibit button.1. import java.util.*;2. class KeyMaster {3. public int i;4. public KeyMaster(int i) { this.i = i; }5. public boolean equals(Object o) { return i == ((KeyMaster)o).i; }6. public int hashCode() { return i; }7. }8. public class MapIt {9. public static void main(String[] args) {10. Set<KeyMaster> set = new HashSet<KeyMaster>();11. KeyMaster k1 = new KeyMaster(1);12. KeyMaster k2 = new KeyMaster(2);13. set.add(k1); set.add(k1);14. set.add(k2); set.add(k2);15. System.out.print(set.size() + ":");16. k2.i = 1;17. System.out.print(set.size() + ":");18. set.remove(k1);19. System.out.print(set.size() + ":");20. set.remove(k2);21. System.out.print(set.size());22. }23. }What is the result?A. 4:4:2:2B. 4:4:3:2C. 2:2:1:0D. 2:2:0:0E. 2:1:0:0F. 2:2:1:1G. 4:3:2:1Answer: FGiven:11. public static void append(List list) { list.add("0042"); }12. public static void main(String[] args) {13. List<Integer> intList = new ArrayList<Integer>();14. append(intList);15. System.out.println(intList.get(0));16. }‘What is the result?A. 42B. 0042C. An exception is thrown at runtime.D. Compilation fails because of an error in line 13.E. Compilation fails because of an error in line 14. Answer: BQuestion 10Given:int[] myArray=newint[] {1, 2,3,4, 5};What allows you to create a list from this array?A. List myList = myArray.asList();B. List myList = Arrays.asList(myArray);C. List myList = new ArrayList(myArray);D. List myList = Collections.fromArray(myArray);Answer: BQuestion 11Given:34. HashMap props = new HashMap();35. props.put("key45", "some value");36. props.put("key12", "some other value");37. props.put("key39", "yet another value");38. Set s = props.keySet();39. // insert code hereWhat, inserted at line 39, will sort the keys in the props HashMap?A. Arrays.sort(s);B. s = new TreeSet(s);C. Collections.sort(s);D. s = new SortedSet(s);Answer: BQuestion 12Given:11. public class Person {12. private String name, comment;13. private int age;14. public Person(String n, int a, String c) {15. name = n; age = a; comment = c;17. public boolean equals(Object o) {18. if(! (o instanceof Person)) return false;19, Person p = (Person)o;20. return age == p.age && name.equals();21. }22. }What is the appropriate definition of the hashCode method in classPerson?A. return super.hashCode();B. return name.hashCode() + age * 7;C. return name.hashCode() + comment.hashCode() /2;D. return name.hashCode() + comment.hashCode() / 2 - age * 3; Answer: BQuestion 13Given:11. public class Key {12. private long id1;13. private long 1d2;14.15. // class Key methods16. }A programmer is developing a class Key, that will be used as a key ina standard java.util.HashMap. Which two methods should be overridden to assure that Key works correctly as a key? (Choose two.)A. public int hashCode()B. public boolean equals(Key k)C. public int compareTo(Object o)D. public boolean equals(Object o)E. public boolean compareTo(Key k)Answer: ADQuestion 14Given:11. public class Person {12. private name;13. public Person(String name) {14. = name;15. }16. public boolean equals(Object o) {17. if( !o instanceof Person ) return false;18. Person p = (Person) o;19. return .equals();20. }Which is true?A. Compilation fails because the hashCode method is not overridden.B. A HashSet could contain multiple Person objects with the same name.C. All Person objects will have the same hash code because the hashCode method is not overridden.D. If a HashSet contains more than one Person object with name="Fred", then removing another Person, also with name="Fred",will remove them all.Answer: BQuestion 15Given:1. public class Person {2. private String name;3. public Person(String name) { = name; }4. public boolean equals(Person p) {5. return .equals();6. }7. }Which is true?A. The equals method does NOT properly override the Object.equals method.B. Compilation fails because the private attribute cannot beaccessed in line 5.C. To work correctly with hash-based data structures, this class mustalso implement the hashCode method.D. When adding Person objects to a java.util.Set collection, the equalsmethod in line 4 will prevent duplicates.Answer: AQuestion 16Which two statements are true about the hashCode method? (Choose two.)A. The hashCode method for a given class can be used to test forobject equality and object inequality for that class.B. The hashCode method is used by the java.util.SortedSet collectionclass to order the elements within that set.C. The hashCode method for a given class can be used to test forobject inequality, but NOT object equality, for that class.D. The only important characteristic of the values returned by ahashCode method is that the distribution of values must follow aGaussian distribution.E. The hashCode method is used by the java.util.HashSet collectionclass to group the elements within that set into hash buckets forswift retrieval.Answer: CEQuestion 17Given:enum Example { ONE, TWO, THREE }Which is true?A. The expressions (ONE == ONE) and ONE.equals(ONE) are both guaranteed to be true.B. The expression (ONE < TWO) is guaranteed to be true and pareTo(TWO) is guaranteed to be less than one.C. The Example values cannot be used in a raw java.util.HashMap; instead, the programmer must use a java.util.EnumMap.D. The Example values can be used in a java.util.SortedSet, but theset will NOT be sorted because enumerated types do NOT implement parable.Answer: AQuestion 18Given:1. public class Score implements Comparable<Score> {2. private int wins, losses;3. public Score(int w, int 1) { wins = w; losses = 1; }4. public int getWins() { return wins; }5. public int getLosses() { return losses; }6. public String toString() {7. return "<" + wins + "," + losses + ">";8. }9. // insert code here10. }Which method will complete this class?A. public int compareTo(Object o) {/*mode code here*/}B. public int compareTo(Score other) {/*more code here*/}C. public int compare(Score s1,Score s2){/*more code here*/}D. public int compare(Object o1,Object o2){/*more code here*/} Answer: BQuestion 19Given:1. public class Test {2. public <T extends Comparable> T findLarger(T x, T y) {3. if(pareTo(y) > 0) {4. return x;5. } else {6. return y;7. }8. }9. }and:22. Test t = new Test();23. // insert code hereWhich two will compile without errors when inserted at line 23? (Choose two.)A. Object x = t.findLarger(123, "456");B. int x = t.findLarger(123, new Double(456));C. int x = t.findLarger(123, new Integer(456));D. int x = (int) t.findLarger(new Double(123), new Double(456)); Answer: ACQuestion 20Given:1. public class Drink implements Comparable {2. public String name;3. public int compareTo(Object o) {4. return 0;5. }6. }and:20. Drink one = new Drink();21. Drink two = new Drink();22. = "Coffee";23. = "Tea";23. TreeSet set = new TreeSet();24. set.add(one);25. set.add(two);A programmer iterates over the TreeSet and prints the name of eachDrink object.What is the result?A. TeaB. CoffeeC. CoffeeTeaD. Compilation fails.E. The code runs with no output.F. An exception is thrown at runtime.Answer: BQuestion 21Given:11. List list = // more code here12. Collections.sort(list, new MyComparator());Which code will sort this list in the opposite order of the sort in line12?A. Collections.reverseSort(list, new MyComparator());B. Collections.sort(list, new MyComparator());list.reverse();C. Collections.sort(list, new InverseComparator(new MyComparator()));D. Collections.sort(list, Collections.reverseOrder(new MyComparator()));Answer: DQuestion 22Given:13. public static void search(List<String> list) {14. list.clear();15. list.add("b");16. list.add("a");17. list.add("c");18. System.out.println(Collections.binarySearch(list, "a"));19. }What is the result of calling search with a valid List implementation?A. 0B. 1C. 2D. aE. bF. cG. The result is undefined.Answer: GQuestion 23Given:1. import java.util.*;2.3. public class LetterASort {4. public static void main(String[] args) {5. ArrayList<String> strings = new ArrayList<String>();6. strings.add("aAaA");7. strings.add("AaA");8. strings.add("aAa");9. strings.add("AAaa");10. Collections.sort(strings);11. for (String s: strings) { System.out.print(s + " "); }12. }13. }What is the result?A. Compilation fails.B. aAaA aAa AAaa AaAC. AAaa AaA aAa aAaAD. AaA AAaa aAaA aAaE. aAa AaA aAaA AAaaF. An exception is thrown at runtime.Answer: CQuestion 24Given:ArrayList a = new ArrayList();containing the values {"1", "2", "3", "4", "5", "6", "7", "8"} Which code will return 2?A. Collections. sort(a, a.reverse());int result = Collections.binarySearch(a, "6");B. Comparator c = Collections.reverseOrder();Collections.sort(a, c);int result = Collections.binarySearch(a, "6");C. Comparator c = Collections.reverseOrder();Collections.sort(a, c);int result = Collections.binarySearch(a, "6",c);D. Comparator c = Collections.reverseOrder(a);Collections.sort(a, c);int result = Collections.binarySearch(a, "6",c);E. Comparator c = new InverseComparator(new Comparator()); Collections.sort(a);int result = Collections.binarySearch(a, "6",c);Answer: CQuestion 25Give:11. public static Iterator reverse(List list) {12. Collections.reverse(list);13. return list.iterator();14. }15. public static void main(String[] args) {16. List list = new ArrayList();17. list.add(" 1"); list.add("2"); list.add("3");18. for (Object obj: reverse(list))19. System.out.print(obj + ",");20. }‘What is the result?A. 3,2, 1,B. 1, 2, 3,C. Compilation fails.D. The code runs with no output.E. An exception is thrown at runtime.Answer: CQuestion 26Given a pre-generics implementation of a method:11. public static int sum(List list) {12. int sum = 0;13. for ( Iterator iter = list.iterator(); iter.hasNext(); ) {14. int i = ((Integer)iter.next()).intValue();15. sum += i;16. }17. return sum;18. }Which three changes must be made to the method sum to use generics? (Choose three.)A. remove line 14B. replace line 14 with "int i = iter.next();"C. replace line 13 with "for (int i : intList) {"D. replace line 13 with "for (Iterator iter : intList) {"E. replace the method declaration with "sum(List<int> intList)"F. replace the method declaration with "sum(List<Integer> intList)"Answer: ACFQuestion 27Given:class A {}class B extends A {}class C extends A {}class D extends B {}Which three statements are true? (Choose three.)A. The type List<A> is assignable to List.B. The type List<B> is assignable to List<A>.C. The type List<Object> is assignable to List<?>.D. The type List<D> is assignable to List<? extends B>.E. The type List<? extends A> is assignable to List<A>.F. The type List<Object> is assignable to any List reference.G. The type List<? extends B> is assignable to List<? extends A>.Answer: CDGQuestion 28Given:11. public void addStrings(List list) {12. list.add("foo");13. list.add("bar");14. }What must you change in this method to compile without warnings?A. add this code after line 11:list = (List<String>) list;B. change lines 12 and 13 to:list.add<String>("foo");list.add<String>("bar");C. change the method signature on line 11 to:public void addStrings(List<? extends String> list) {D. change the method signature on line 11 to:public void addStrings(List<? super String> list) {E. No changes are necessary. This method compiles without warnings.Answer: DQuestion 29Given:1. import java.util.*;2. public class Test {3. public static void main(String[] args) {4. List<String> strings = new ArrayList<String>();5. // insert code here6. }7. }Which four, inserted at line 5, will allow compilation to succeed?(Choose four.)A. String s = strings.get(0);B. Iterator i1 = strings.iterator();C. String[] array1 = strings.toArray();D. Iterator<String> i2 = strings.iterator();E. String[] array2 = strings.toArray(new String[1]);F. Iterator<String> i3 = strings.iterator<String>(); Answer: ABDEQuestion 30Given:1. import java.util.*;2. public class Old {3. public static Object get()(List list) {4. return list.get(0);5. }6. }Which three will compile successfully? (Choose three.)A. Object o = Old.get0(new LinkedList());B. Object o = Old.get0(new LinkedList<?>());C. String s = Old.getfl(new LinkedList<String>());D. Object o = Old.get0(new LinkedList<Object>());E. String s = (String)Old.get0(new LinkedList<String>()); Answer: ADEQuestion 31Given:11. // insert code here12. private N min, max;13. public N getMin() { return min; }14. public N getMax() { return max; }15. public void add(N added) {16. if (min == null || added.doubleValue() <min.doubleValue())17. min = added;18. if (max == null ||added.doubleValue() > max.doubleValue())19. max = added;20. }21. }Which two, inserted at line 11, will allow the code to compile? (Choosetwo.)A. public class MinMax<?> {B. public class MinMax<? extends Number> {C. public class MinMax<N extends Object> {D. public class MinMax<N extends Number> {E. public class MinMax<? extends Object> {F. public class MinMax<N extends Integer> {Answer: DFQuestion 32A programmer must create a generic class MinMax and the type parameter of MinMax must implement Comparable. Which implementation of MinMax will compile?A. class MinMax<E extends Comparable<E>> {E min=null;E max=null;public MinMax() { }public void put(E value) { /* store min or max */ }}B. class MinMax<E implements Comparable<E>> {E min=null;E max=null;public MinMax() { }public void put(E value) { /* store min or max */ }}C. class MinMax<E extends Comparable<E>> {<E> E min = null;<E> E max = null;public MinMax() { }public <E> void put(E value) { /* store min or max */ }}D. class MinMax<E implements Comparable<E>> {<E> E min = null;<E> E max = null;public MinMax() { }public <E> void put(E value) { /* store min or max */ }}Answer: A二、拖拽题:Question 1:Answer:Allows access to elements by their integer index------------------java.util.List------------------defines the method V get(Object key)------------------java.util.Map------------------is designed for holding elements prior to processing------------------java.util.Queue------------------contains no pair of elements e1 and e2, such that e1.equals(e2) ------------------java.util.Set------------------Question 2:Place the code into position to create a class that maps from Strings to integer values.The result of execution must be [one]. Some options may be used more than once.Answer:public class NumberNames{private HashMap<String,Integer>map=new HashMap<String,Integer>;public void put(String name,int value){map.put(name,value);}public Set<String> getNames(){return map.keySet();}}Question 3:Answer: m1(listA); Compiles and runs without errorm2(listA); Compiles and runs without errorm1(listB); Compiles and runs without errorm2(listB); Compilation failsm1(listO); Compilation failsm2(listO); Compilation failsQuestion 4:Place the code in the appropriate place such that this program will always output [1, 2].Answer: import java.util.*;public class MyInt implements Comparable{ public static void main(String[] args) { ArrayList<MyInt> list=new ArrayList<MyInt>(); list.add(new MyInt(2));list.add(new MyInt(1));Collections.sort(list);System.out.println(list);}private int i;public MyInt(int i){this.i=i;}public String toString(){return Integer.toString(i);}public int compareTo(Object o) {MyInt i2=(MyInt)o;return i-i2.i;}}Question 5:Given the class definitions:Place the correct Compilation Result on each takeList() method definition to indicate whether or not the go() method would compile given that definition.Answer:public void takeList(ArrayList list){}-----------------------------Compilation succeedspublic void takeList(ArrayList<Dog> list) {}---------------------Compilation succeedspublic void takeList(ArrayList<Animal> list) {}-----------------Compilation failspublic void takeList(ArrayList<? extends Animal> list){}------Compilation succeedspublic void takeList(ArrayList<?> list){}-------------------------Compilation succeedspublic void takeList(ArrayList<Object> list){}------------------Compilation failsQuestion 6:Answer:public class GenericB<T extends Pet>{ public T foo;public void setFoo(T foo){this.foo = foo;}public T getFoo(){return foo;}}Question 7:Answer:ArrayList<String> x1=new ArrayList<String>();foo(x1); //Compilation of the first statement succeeds, but compilation failsdue to an error in the second statementArrayList<Object> x2=new ArrayList<String>();foo(x2); //Compilation fails due to an error in the first statement.ArrayList<Object> x3=new ArrayList<Object>();foo(x3); //Compilation succeedsArrayList x4=new ArrayList();foo(x4); //Compilation succeedsQuestion 8:Answer:public class Gen<T>{ private T object; public Gen(T object){ this.object = object; }public T getObject(){ return object;}}Question 9:Answer:list.add("Foo"); Compilation failslist = new ArrayList<String>(); Compilation succeeds list = new ArrayList<Object>(); Compilation fails String s = list.get(0); Compilation succeedsObject o = list; Compilation succeedsQuestion 10:Answer:import java.util.*;public class _166 {public static void main(String[] args) { List<String> list=new LinkedList<String>(); list.add("one");list.add("two");System.out.println(list.get(0).length());}}。
任务一:用LinkedList存放对象1.利用面向对象的思想,创建以下类:●Person类,包含Person的姓名和身份证号码,覆盖Object类的toString()方法,显示“姓名:XXX 身份证号:XXX”。
●Student类,继承Person类,包含学生的语文、数学、英文课的成绩,并覆盖父类的toString()方法,显示“姓名:XXX 身份证号:XXX 语文:XXX 数学:XXX 英文:XXX”。
●Teacher类,继承Person类,包含教师的工资。
并覆盖父类的toString()方法,显示“姓名:XXX 身份证号:XXX 工资:XXX”。
●public class Person implements Comparable{●String name;●String ID;●Person(String s,String i){●name=s;●ID=i; }●public String toString() {●String str="姓名:"+name+" 身份证号码:"+ID;●return str; }●public int compareTo(Object arg0) {●Person p=(Person)arg0;●return pareTo(p.ID); } }●class Student extends Person {●int Chinese;●int Math;●int English;●Student(String n,String i,int c,int m,int e){●super(n,i);●Chinese=c;●Math=m;●English=e; }●public String toString() {●String str;●str=" 语文成绩:"+Chinese+" 数学成绩:"+Math+" 英语成绩:"+English;●return super.toString()+str;●}●}●class Teacher extends Person{●int salary;●Teacher(String n,String i,int s){●super(n,i);●salary=s;●}●public String toString() {●String str=" 工资"+salary;●return super.toString()+str;●} }2.分别为以上三个类创建对象:3.将这三个对象存放在一个LinkedList对象中:LinkedList<Person> list=new LinkedList<Person>();4.运行示例:public class MyList {public static void main(String[] args) {LinkedList<Person> m=new LinkedList<Person>();Person p=new Person("张三","12310000");Student s=new Student("李四","12320000",89,93,94);Teacher t=new Teacher("王五","12330000",3000);m.add(p);m.add(s);m.add(t);Iterator<Person> i = m.iterator();while(i.hasNext()){System.out.println(i.next());}}}5.练习使用LinkedList的其他方法。
Java基础之集合测试单选题:(每道题目2分)1.下面哪个不是集合和数组的区别?a:集合长度可变b:子集就可以存储提及数据类型c:子集就可以存储一种提及数据类型d:子集可以存储相同提及数据类型2.collection中contains()方法的作用是?a:往集合中添加元素b:从集合中删除元素c:推论元素在子集中与否存有d:推论子集与否为空3.下面关于迭代器,说法错误的是?a:专门用于遍历数组b:专门用于遍历集合c:依赖于集合而存在d:内部类的方式实现4.list子集元素的特点就是?a:元素有序b:元素无序c:元素不容重复d:元素自然排序5.list集合的get()方法的作用是?a:获取第一个位置的元素b:获取最后一个位置的元素c:获取指定位置的元素d:获取中间位置的元素6.concurrentmodificationexception就是什么东西?a:空指针异常b:出访越界异常c:初始化异常d:mammalian修正异常7.下面哪个不属于常见的数据结构?a:栈b:队列c:链表d:圆8.arraylist子集的底层数据结构就是?a:数组b:链表c:哈希表中d:红黑一棵9.下面哪个不是vector的特有功能?a:addelement()b:add()c:elementat()d:elements()10.vector集合的特点是?a:线程同步b:线程不同步c:增删快d:底层结构就是链表11.linkedlist集合的特点是?a:查询快b:增删快c:元素唯一d:元素按比较器排序12.下面代码运行的结果是?arraylistal=newarraylist();al.add(true);al.add(123);al.add(\system.out.prin tln(al);a:编译失败b:[true,123,abc]c:[true,123]d:[abc]13.arraylist子集和vector子集的区别观点恰当的就是?a:arraylist就是线程安全的,vector就是线程不安全的b:arraylist就是线程不安全的,vector就是线程安全的c:arraylist底层结构就是数组,vector底层结构就是链表d:arraylist底层结构就是链表,vector底层结构就是数组14.下面代码运行的结果是?arraylistal=newarraylist();al.add(“a”);al.add(“b”);al.add(“c”);iteratorit=al.iterator();while(it.hasnext()){strings=(string)it.next();if(s.equals(“c”)){al.add(“c1”);}}system.out.println(al)a:编译失败b:[a,b,c]c:[a,b,c,c1]d:抛出concurrentmodificationexception异常15.set子集的特点就是?a:元素有序b:元素无序c:元素可以重复d:元素从大到小排序16.有关hashset子集的观点恰当的就是?a:底层数据结构就是链表b:底层数据结构就是数组c:元素就是重复的d:确保元素的唯一性依赖hashcode()和equals()17.有关treeset集合的说法错误的是?a:底层数据结构是红黑树b:元素可重复c:可以通过自然排序对元素进行排序d:可以通过比较器排序对元素进行排序18.有关map子集观点错误的就是?a:map子集由键值对共同组成b:map子集的键可以重复c:map子集的值可以重复d:map子集不是collection子集的子体系19.下面关于hashmap说法正确的是?a:底层数据结构是链表b:底层数据结构是数组c:可以允许null键和null值d:不允许null键和null值20.linkedhashmap子集的底层数据结构就是?a:数组b:栈c:红黑树d:链表和哈希表中多选题:(每道题目3分)21.下面哪些方法就是arraylist和linkedlist都有的?a:add()b:addfirst()c:get()d:iterator()22.以下有关增强for的说法正确的是?a:增强for是jdk5的新特性b:增强for可以直接遍历数组c:增强for可以直接遍历map集合d:进一步增强for可以轻易结点collection子集23.下面关于泛型的说法正确的是?a:泛型是jdk5的新特性b:泛型增强了程序的安全性c:泛型避免了强制类型转换d:泛型要求必须强制类型转换24.arraylist子集可以通过下面哪些方式展开结点a:iterator运算器同时实现b:进一步增强for同时实现c:get()和length()方法结合实现d:get()和size()方法结合实现25.map子集可以通过哪些方式展开结点?a:轻易通过运算器即可b:根据键找值的方式c:根据for循环轻易结点d:根据键值对对象打听键和值的方式简答题目:(每道题目3分)26:arraylist,vector以及linkedlist的特点?arraylist:底层数据结构是数组,查询快,增删慢线程不安全,效率高vector:底层数据结构就是数组,查阅慢,更动快线程安全,效率高linkedlist:底层数据结构是链表,查询慢,增删快线程不安全,效率高27:hashmap和hashtable的区别?a:hashmap线程不安全,效率高。
java 泛型试题Java泛型试题一、选择题1. 能使用泛型的是?A. 类B. 方法C. 接口D. 所有上述选项2. 下列关键字中用于定义泛型的是?A. classB. interfaceC. extendsD. <>3. 在Java中,泛型的作用是?A. 提高代码的可读性B. 提供编译时的类型检查C. 支持不同类型对象的统一操作D. 所有上述选项4. 下面哪个选项是泛型类的正确声明方式?A. class MyGenericClass<T, U>B. class MyGenericClass<T, U> extends MyGenericClass<T>C. class MyGenericClass extends T, UD. class MyGenericClass<T extends U>5. 下面哪个选项是泛型方法的正确声明方式?A. public void myMethod<T>(T value)B. public <T> void myMethod(T value)C. public void myMethod(T value) <T>D. public <T> void myMethod(void value)二、填空题1. 在泛型类中,T是什么意思?答:T代表类型参数,可以是任意指定的类型,比如T可以代表String、Integer等。
2. 在泛型方法中,可以使用什么字符代表类型参数?答:使用尖括号<>内的大写字母来表示类型参数,比如<T>。
3. 泛型类可以同时定义多个类型参数吗?是的话,应该怎么定义?答:是的,泛型类可以同时定义多个类型参数。
格式为class MyClass<T, U, V>。
4. 什么是泛型通配符?它的作用是什么?答:泛型通配符是一种特殊的类型参数,用`?`表示。
JavaSet练习题一、基本概念1. 请说明Set集合的特点。
2. 请列举Java中常用的Set实现类及其特点。
3. 请解释Set集合中的元素为什么不能重复。
二、HashSet4. 编写一个Java程序,使用HashSet存储10个字符串元素,并打印所有元素。
5. 编写一个Java程序,使用HashSet存储10个Integer类型的元素,并删除重复的元素。
6. 编写一个Java程序,使用HashSet存储自定义对象,并重写equals()和hashCode()方法。
三、LinkedHashSet7. 编写一个Java程序,使用LinkedHashSet存储10个字符串元素,并按照元素插入顺序打印所有元素。
8. 编写一个Java程序,使用LinkedHashSet存储10个Integer 类型的元素,并删除重复的元素,保持插入顺序。
四、TreeSet9. 编写一个Java程序,使用TreeSet存储10个字符串元素,并按照字典顺序打印所有元素。
10. 编写一个Java程序,使用TreeSet存储自定义对象,并实现Comparable接口。
11. 编写一个Java程序,使用TreeSet存储10个Integer类型的元素,并按照升序打印所有元素。
五、Set操作12. 编写一个Java程序,使用HashSet存储10个字符串元素,然后使用removeIf()方法删除所有长度大于5的元素。
13. 编写一个Java程序,使用HashSet存储10个字符串元素,然后使用retainAll()方法保留与另一个HashSet相同的元素。
14. 编写一个Java程序,使用HashSet存储10个字符串元素,然后使用addAll()方法将另一个HashSet的元素添加到当前HashSet 中。
六、集合转换15. 编写一个Java程序,将HashSet转换为ArrayList,并打印ArrayList中的所有元素。
关于Java泛型的面试题1. Java中的泛型是什么? 使用泛型的好处是什么?这是在各种Java泛型面试中,一开场你就会被问到的问题中的一个,主要集中在初级和中级面试中。
那些拥有Java1.4或更早版本的开发背景的人都知道,在集合中存储对象并在使用前进行类型转换是多么的不方便。
泛型防止了那种情况的发生。
它提供了编译期的类型安全,确保你只能把正确类型的对象放入集合中,避免了在运行时出现ClassCastException。
2. Java的泛型是如何工作的? 什么是类型擦除?这是一道更好的泛型面试题。
泛型是通过类型擦除来实现的,编译器在编译时擦除了所有类型相关的信息,所以在运行时不存在任何类型相关的信息。
例如List在运行时仅用一个List来表示。
这样做的目的,是确保能和Java 5之前的版本开发二进制类库进行兼容。
你无法在运行时访问到类型参数,因为编译器已经把泛型类型转换成了原始类型。
根据你对这个泛型问题的回答情况,你会得到一些后续提问,比如为什么泛型是由类型擦除来实现的或者给你展示一些会导致编译器出错的错误泛型代码。
请阅读我的Java中泛型是如何工作的来了解更多信息。
3. 什么是泛型中的限定通配符和非限定通配符?这是另一个非常流行的Java泛型面试题。
限定通配符对类型进行了限制。
有两种限定通配符,一种是它通过确保类型必须是T的子类来设定类型的上界,另一种是它通过确保类型必须是T的父类来设定类型的下界。
泛型类型必须用限定内的类型来进行初始化,否则会导致编译错误。
另一方面表示了非限定通配符,因为可以用任意类型来替代。
更多信息请参阅我的文章泛型中限定通配符和非限定通配符之间的区别。
4. List和List 之间有什么区别?这和上一个面试题有联系,有时面试官会用这个问题来评估你对泛型的理解,而不是直接问你什么是限定通配符和非限定通配符。
这两个List的声明都是限定通配符的例子,List可以接受任何继承自T 的类型的List,而List可以接受任何T的父类构成的List。
集合测试练习卷(总3页)--本页仅作为文档封面,使用时请直接删除即可----内页可以根据需求调整合适字体及大小--集合专项检测一、填空题:(本大题共有4小题,每小题5分,共20分)1. 如果全集}6,5,4,3,2,1{=U 且}2,1{)(=⋂B C A U ,}5,4{)()(=⋂B C A C U U ,}6{=⋂B A ,则A 等于_________2. 若集合{}2,12,4a a A --=,{}9,1,5a a B --=,且{}9=B A ,则a 的值是________;3.若集合},01|{},06|{2=-==-+=ax x N x x x M 且M N ⊆,则a 的值为_________.4.已知集合._________}023)1(|{2==-+-=a x x a x A 实数有且仅有两个子集,则二、选择题(本大题共有8小题,每小题5分,共40分,在每小题给出的四个选项中,只有一项是符合要求的.) 5.已知集合M={x N|4-x N}∈∈,则集合M 中元素个数是( )A .3B .4C .5D .66.集合}22{<<-=x x A ,}31{<≤-=x x B ,那么=⋃B A ( ) A. }32{<<-x x B.}21{<≤x x C.}12{≤<-x x D.}32{<<x x7.已知集合}01|{2=-=x x A ,则下列式子表示正确的有( ) ①A ∈1②A ∈-}1{ ③A ⊆φ ④A ⊆-}1,1{ A .1个 B .2个 C .3个 D .4个8.*}*,,5|),{(N y N x y x y x P ∈∈=+=,则集合的非空子集个数( )9. 设集合) (B A 0},32x |{x },034|{2=⋂>-=<+-=则B x x x A A.}233|{-<<-x x B.}233|{<<-x x C. }231|{<<x x D.}323|{<<x x 10.如图所示,I 是全集,M ,P ,S 是I 的三个子集,则阴影部分所表示的集合是( )A .()M P S ⋂⋂ B .()M P S ⋂⋃ C .()I (C )M P S ⋂⋂D .()I (C )M P S ⋂⋃ 11.已知集合==+==x B A n m m B m n m A 则若,},0,,{},1,,{2( ) =1,n=0 =-1,n=1 =-1,n=0 =1,n=-112.已知集合M={x|x 1},N={x|x>}a ≤-,若M N ≠∅,则有( )A .1a <-B .1a >-C . 1a ≤-D .1a ≥-三、解答题(本大题共有5小题,共40分.解答应写出文字说明,证明过程或演算步骤)21. (本小题8分)已知:集合}12|{},31|{m x m x B x x A -<<=<<=集合.(1)当;1B A m ⋃-=时,求)(B C A R ⋂;)()(B C A C R R ⋂(2)的取值范围;求实数若m B A ,⊆22. (本小题8分)已知集合2{|320}A x x x =-+=,}{012=-+-=m mx x x B .若A B A =,求实数m 的取值范围。
选择题
1.在java中,( C )对象可以使用键/值的形式保存数据。
A:ArrayList
B: HashSet
C: HashMap
D: LinkedList
2.创建一个类,来存储唯一的对象元素,元素不需要保持特定顺序,但是必须唯一。
最
能满足这种要求的接口是:( AE ) 。
(多选)
A、Set
B、List
C、Map
D、Array
E、HashSet
3.以下不属于ArrayList的方法的是(C )
A: add() B: addAll()
C: addFirst() D: size();
4.下列声明语句错误的是(C )
A : List list=new ArrayList()
B: List<String> list=new LinkedList();
C: ArrayList al= new List();
D: Set set=(Set)new ArrayList()
5.欲构造ArrayList 类的一个实例,此类继承了List 接口,下列哪个方法是正确的(B )。
A: ArrayList myList=new Object( )
B: List myList=new ArrayList( )
C: ArrayList myList=new List( )
D: List myList=new List( )
填空题
6.Iterator通过调用hasNext() 判断是否有下一元素,并通过next() 方法取得
下一元素。
判断题
7.ArrayList 和LinkedList 都实现Cloneable 接口,都提供了两个构造函数,一个无参
的,一个接受另一个Collection。
(√)
8.Map接口不是Collection接口的继承(√)
简答题
9.List, Set, Map是否继承自Collection接口?
答:List,Set继承自Collection,Map不是。
List,Map比较常用:List是通过下标来访问元素,Map是通过键值进行访问元素。
应该不会同时都实现了Collection接口.
Collection是一个什么概念?还有Set在java中是怎样定义的?他是通过下标来访问元素还是通过键值来访问元素?
两者谁继承了Collection接口呢?或者有没有可能两者都继承了Collection接口?
时间不多了,我是这样写的:
Set,Map实现了Collection接口。
而List不需要实现Collection接口。
10.Collection 和Collections的区别。
答:Collection是一个接口,Collections是一个集合对象的工具类。
Collection是集合类的上级接口,继承于他的接口主要有Set 和List.Collections是针对集合类的一个帮助类,它提供一系列静态方法实现对各种集合的搜索、排序、线程安全化等操作。