Java集合和泛型练习及面试题——博客园:师妹开讲啦

给定一段JAVA代码如下:要打印出list中存储的内容,以下语句正确的是( B )

ArrayList list = new ArrayList( )

list.add(“a”)

list.add(“b”)

Iterator it = list.iterator( )

A.while(it. Next( ) )   system.out.println(it.next( ) )

B.for(int i=0; i<list.size( ) i++)   system.out.println(list.get(i))

C.while(list.hasNext( ) )   system.out.println(list.next( ) )

D.for(int i=0; i<list.size( ) i++)   system.out.println(it(i))

下面代码运行结果正确的是(C )--博客园:师妹开讲啦

import java.util.*;

public class TestListSet{

  public static void main(String args[]){

    List list = new ArrayList();

    list.add(“Hello”);

    list.add(“Learn”);

     list.add(“Hello”);

     list.add(“Welcome”);

    Set set = new HashSet();

    set.addAll(list);

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

  }

}

A.编译不通过                   B.编译通过,运行时异常  

C.编译运行都正常,//输出HashSet中不能放重复值  D.编译运行都正常,输出4

在java中,( B)接口位于集合框架的顶层

A.Map  B.Collection  C.Set  D.List

在JAVA中,以下( C )类的对象以键-值的方式存储对象

A.java.util.List   B.java.util.ArrayList  C.java.util.HashMap  D.java.util.LinkedList

在JAVA中ArrayList类实现了可变大小的数组,便于遍历元素和随机访问元素,已知获得了ArrayList类的对象bookTypeList,则下列语句中能够实现判断列表中是否存在字符串“小说”的是(C )

A.bookTypeList.add("小说");       B.bookTypeList.get("小说");

C.bookTypeList.contains("小说");    D.bookTypeList.remove("小说");

下面叙述哪些是正确的?(ABC )

A.java中的集合类(如Vector)可以用来存储任何类型的对象,且大小可以自动调整。但需要事先知道所存储对象的类型,才能正常使用

B.在java中,可以用异常(Exception)来抛出一些并非错误的消息,但这样比直接从函数返回一个结果要花费更大的系统开销。

C.java接口包含函数声明和常量声明。

D.java中,子类不可以访问父类的私有成员和受保护的成员

在JAVA中,LinkedList类和ArrayList类同属于集合框架类,下列(ABC )选项中的方法是LinkedList类ArrayList类都有的

A.add(Object o)  B.add(int index,Object o)  C.remove(Object o)   D.removeLast()

请分析下面程序编译并运行的结果

class MyNumberException<T> extends Exception{

  public MyNumberException(String message){

    super(message);

  }

}

public class GenericsTest{

  public static void main(String[] args){

    int num=1;

    try{

      if(num<10){

        throw new MyNumberException("数字小于10");

      }

    }catch(MyNumberException e){

      System.out.println(e);

    }catch(Exception e){

      System.out.println(e);

    }

  }

}

解析:在Java中泛型类继承Throwable及其子类都是不合法的,所以上面的程序编译无法通过

已知:--博客园:师妹开讲啦

public class ListTest{

  public static void main(String[] args){

    LinkedList<String> link=new LinkedList<String>();

    link.add("1");

    link.add("2");

    link.add("3");

    link.addFirst("F");

    link.addLast("L");

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

      link.remove(i);

    }

    System.out.println(link);

  }

}

程序运行结果:[1,3]

解析:添加完元素后,集合中的元素顺序为[F,1,2,3,L],各个元素对应索引位置为0,1,2,3,4 执行第一次循环,i=0,删除F,集合变为[1,2,3,L],各个元素对应的索引位置为0,1,2,3 执行第二次循环:i=1,删除2,集合变为[1,3,L],各个元素对应的索引位置为0,1,2 执行第三次循环:i=2,删除L,集合变为[1,3],各个元素对应的索引位置为0,1 所以程序结束,结果为[1,3]

利用Map,完成下面的功能:

从命令行读入一个字符串,表示一个年份,输出该年的世界杯冠军是哪支球队。如果该年没有举办世界杯,则输出:没有举办世界杯。

附:世界杯冠军以及对应的夺冠年份--博客园:师妹开讲啦

public class Bk {

  public static void main(String[] args) {

    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

    String year=null;

    try {

      year=br.readLine();

    } catch (IOException e) {

      e.printStackTrace();

    }

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

    map.put("2002", "巴西");

    map.put("2006", "意大利");

    map.put("2010","南非");

    if(map.containsKey(year)){

      System.out.println(map.get(year));

    }

    else{

      System.out.println("这一年没有承办世界杯!");

    }

  }

}

完善下列代码,实现把List 中的内容放到一个Map 中,该Map 的键为id值为相应的Account 对象。最后遍历这个Map,打印所有Account 对象的id 和余额

public class Test{

  public static void main(String[] args) {

    List list=new ArrayList();

    list.add(new Account(10.00,"1234"));

    list.add(new Account(15.00,"5678"));

    list.add(new Account(0.0,"1010"));

    Map map=new HashMap();

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

      Account account=(Account)list.get(i);

      map.put(account.getId(), account);

    }

    Set<Map.Entry<Long,Object>> set=map.entrySet();

    for(Map.Entry<Long, Object> obj:set){

      Account acc=(Account)obj.getValue();

      System.out.println(obj.getKey()+"/"+acc.getBalance());

    }

  }

}

class Account{

  private long id;

  private double balance;

  private String password;

  public Account(){}

  public Account(double balance,String password){

    this.id=new Random().nextLong();

    this.balance=balance;

    this.password=password;

  }

  public long getId() {

    return id;

  }

  public void setId(long id) {

    this.id = id;

  }

  public double getBalance() {

    return balance;

  }

  public void setBalance(double balance) {

    this.balance = balance;

  }

  public String getPassword() {

    return password;

  }

  public void setPassword(String password) {

    this.password = password;

  }

}

写出下面程序的输出结果

import java.util.*;

class MyClass{

  int value;

  public MyClass(){}

  public MyClass(int value){

    this.value = value;

  }

  public String toString(){

    return value;

  }

}

public class TestList{

  public static void main(String args[]){

    MyClass mc1 = new MyClass(10);

    MyClass mc2 = new MyClass(20);

    MyClass mc3 = new MyClass(30);

    List list = new ArrayList();

    list.add(mc1);

    list.add(mc2);

    list.add(mc3);

    MyClass mc4 = (MyClass) list.get(1);

    //MyClass mc4=(MyClass)mc2;

    mc4.value = 50;

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

      System.out.println(list.get(i));

    }

  }

}

程序运行结果:

10

50

30

使用HashMap完成学生信息的管理功能,主要功能包括:添加学生数据、打印学生名单、删除学生数据、按学号查询学生信息四个功能。并实现持久化保存--博客园:师妹开讲啦

//Java序列化是指把Java对象转换为字节序列的过程;而Java反序列化是指把字节序列恢复为Java对象的过程

public class Student implements Serializable{

private static final long serialVersionUID = 1L;

private String sno;

private String name;

private String gender;

private int age;

public Student(String sno,String name,String gender,int age){

super();

this.sno=sno;

this.name=name;

this.gender=gender;

this.age=age;

}

public String getSno() {

return sno;

}

public void setSno(String sno) {

this.sno = sno;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getGender() {

return gender;

}

public void setGender(String gender) {

this.gender = gender;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public String toString(){

return sno+"\t"+name+"\t"+gender+"\t"+age;

}

}

public interface DAOStudent {

public boolean saveAll(HashMap<String, Student> students);

public HashMap<String, Student> getAll();

}

public class ImplDAOStudent implements DAOStudent{

@Override

public HashMap<String, Student> getAll() {

HashMap<String,Student> hm=new HashMap<String, Student>();

File file=new File("student.txt");

ObjectInputStream ois=null;

try{

ois=new ObjectInputStream(new FileInputStream(file));

if(file.length()!=0){

hm=(HashMap<String, Student>)ois.readObject();

}

ois.close();

}catch(Exception e){

e.printStackTrace();

}

return hm;

}

@Override

public boolean saveAll(HashMap<String, Student> students){

File file=new File("student.txt");

long l=file.length();

ObjectOutputStream oos=null;

try{

oos=new ObjectOutputStream(new FileOutputStream(file));

oos.writeObject(students);

oos.close();

}catch(Exception e){

e.printStackTrace();

}

if(file.length()>l){

return true;

}

else {

return false;

}

}

}

public class StudentControl {

private static DAOStudent DAOstu=new ImplDAOStudent();

private static HashMap<String,Student> students;

public static StudentControl st=new StudentControl();

static{

students=DAOstu.getAll();

}

private StudentControl(){}

public static StudentControl getInstance(){

return st;

}

public boolean addStudent(Student s){

if(!students.containsKey(s.getSno())){

students.put(s.getSno(), s);

return true;

}else{

return false;

}

}

public ArrayList<Student> getAll(){

ArrayList<Student> al=new ArrayList<Student>();

Set<Map.Entry<String, Student>> set=students.entrySet();

Iterator<Map.Entry<String,Student>> it=set.iterator();

while(it.hasNext()){

Map.Entry<String,Student> entry= it.next();

Student stu=entry.getValue();

al.add(stu);

}

return al;

}

public boolean deleteStudent(String sno){

if(students.containsKey(sno)){

students.remove(sno);

return true;

}else{

return false;

}

}

public Student queryStudentBySno(String sno){

if(students.containsKey(sno)){

return students.get(sno);

}else

return null;

}

public boolean exitSystem(){

return DAOstu.saveAll(students);

}

}

public class ViewStudent {

public void menu(){

System.out.println("*********************");

System.out.println("请选择需要的功能:");

System.out.println("1.添加学生数据");

System.out.println("2.打印学生名单");

System.out.println("3.删除学生数据");

System.out.println("4.打印对应学号的学生数据");

System.out.println("0.退出系统");

System.out.println("**********************");

}

}

public class ManageStudent{

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

StudentControl sco=StudentControl.getInstance();

while(true){

new ViewStudent().menu();

int count=sc.nextInt();

switch(count){

case 1: System.out.println("请输入学生信息:");

System.out.print("姓名:");

String name=sc.next();

System.out.print("学号:");

String sno=sc.next();

System.out.print("性别:");

String gender=sc.next();

System.out.print("年龄:");

int age=sc.nextInt();

Student student=new Student(sno,name,gender,age);

if(sco.addStudent(student)){

System.out.println("操作成功");

}else{

System.out.println("操作失败");

}

break;

case 2:

System.out.println("学号\t\t姓名\t性别\t年龄");

ArrayList<Student> list=sco.getAll();

Iterator<Student> it=list.iterator();

while(it.hasNext()){

Student stu=it.next();

System.out.println(stu.toString());

}

break;

case 3:System.out.println("请输入需要删除的学生的学号:");

String string=sc.next();

if(sco.deleteStudent(string)){

System.out.println("操作成功");

}else{

System.out.println("操作失败");

}

break;

case 4:System.out.println("输入你要查找的学号:");

String str=sc.next();

Student stu=sco.queryStudentBySno(str);

System.out.println("学号\t\t姓名\t性别\t年龄");

System.out.println(stu.toString());

break;

case 0:

sco.exitSystem();

System.exit(0);

default:System.out.println("输入有误,请重新输入");

}

}

}

}

输入学生信息,按学生成绩排序

public class Stu{

private String name;

private int score;

public Stu(){}

public Stu(String name,int score){

this.name=name;

this.score=score;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getScore() {

return score;

}

public void setScore(int score) {

this.score = score;

}

public String toString(){

return name+":"+score;

}

}

public class CompareScore implements Comparator<Stu>{

public boolean equals(Object obj){

return super.equals(obj);

}

@Override

public int compare(Stu s1, Stu s2) {

if(s1.getScore()>s2.getScore()){

return -1;

}else if(s1.getScore()<s2.getScore()){

return 1;

}else{

return s2.getName().compareTo(s1.getName());

}

}

}

public class DemoTreeSet {

public static void main(String[] args) {

Scanner sc=new Scanner(System.in);

TreeSet<Stu> ts=new TreeSet<Stu>(new CompareScore());

while(true){

System.out.print("给出你的选择(1.添加信息、2.降序输出、3.退出程序):");

int num=sc.nextInt();

switch(num){

case 1:

System.out.print("输入学生的姓名:");

String name=sc.next();

System.out.print("输入学生的成绩:");

int score=sc.nextInt();

ts.add(new Stu(name,score));

break;

case 2:System.out.println(ts);

break;

case 0:System.exit(0);

default:System.out.println("输入有误,请重新输入");

}

}

}

}

使用泛型得到数组的最大和最小值

interface MaxOrMin<T extends Comparable<T>>{

T min(T[] t);

T max(T[] t);

}

public class TextMinOrMax {

public static void main(String[] args) {

Integer[] in=new Integer[]{43,52,66,71,39,33};

Character[] ch=new Character[]{'f','v','d','t','z'};

ComparableElement<Integer> ce1=new ComparableElement<Integer>();

System.out.println("int数组的最大值:"+ce1.max(in)+",最小值:"+ce1.min(in));

ComparableElement<Character> ce2=new ComparableElement<Character>();

System.out.println("char数组的最大值:"+ce2.max(ch)+",最小值:"+ce2.min(ch));

}

}

class ComparableElement<T extends Comparable<T>> implements MaxOrMin<T>{

T max;

T min;

@Override

public T max(T[] t) {

max=t[0];

for(int i=0;i<t.length;i++){

if(max.compareTo(t[i])<0){

max=t[i];

}

}

return max;

}

@Override

public T min(T[] t) {

min=t[0];

for(int i=0;i<t.length;i++){

if(min.compareTo(t[i])>0){

min=t[i];

}

}

return min;

}

}

Iterator与ListIterator有什么区别?

Iterator:只能正向遍历集合,适用于获取移除元素。ListIerator:继承Iterator,可以双向列表的遍历,同样支持元素的修改。

Collection和Collections的区别

答:Collection:是java.util包中的接口,是集合类的基本接口,主要的子接口有List和Set

Collections:是java.util包中的类,是针对集合的一个实用工具类,它包含了对各种集合的搜索、排序和线程安全等一系列的静态方法。

ArrayList与Vector的异同--博客园:师妹开讲啦

答:相同点:ArrayList和Vector都是List的子类,都是有序的集合,可以存储相同的元素,相当于动态数组,他们都可以按索引位置取得指定的元素。

区别:(1)出现的时间:Vector是在JDK1.0就已存在,而ArrayList到了JDK1.2才推出。

(2)同步性:Vector是线程安全的,也就是说它的方法之间是线程同步的,而ArrayList是线程不安全的,它的方法之间是线程不同步的。在程序设计中,如果是只有一个线程会访问到集合,最好选择使用ArrayList,因为他不考虑线程安全,效率会高些;如果多个线程会访问到集合,最好选择使用Vector,因为不需要开发人员自己编写线程安全的代码。

(3)数据增长:ArrayList与Vector都存在初始的容量大小,且都为10,当存储进集合里的元素的个数超过了容量时,就需要增加ArrayList与Vector的存储空间。每次要增加存储空间时,不是只增加一个存储单元,而是增加多个存储单元。这就要求每次增加的存储单元的个数在内存空间利用与线程效率之间要取得一定的平衡。Vector默认增长为原来一倍,而ArrayList的增长策略在文档中没有明确规定(从源代码看到的是增长为原来的一半)

(4)输出方式:Vector可以使用Iterator、foreach和Enumeration方式输出,而ArrayList只能使用Iterator、foreach方式输出

简述HashMap与Hashtable的异同--博客园:师妹开讲啦

答:相同点:HashMap与Hashtable都是Map接口的实现类,而HashMap是Hashtable的轻量级实现(非线程安全的实现)。两者都是用key-value方式获取数据。

区别:(1)出现的时间:Hashtable在JDK1.0时出现,属于旧的操作类,而HashMap是在JDK1.2时推出的类,属于较新的操作类

(2)同步性:Hashtable是线程安全的,也就是说是同步的,性能相对较低,而HashMap是线程不安全的,不是同步的,性能相对较高。

(3)值:Hashtable不允许存放null值和null键,而HashMap允许存在一个null键和多个null值

(4)HashMap没法保证映射的顺序一直不变,但是作为HashMap的子类LinkedHashMap,如果想要预知的顺序迭代(默认按照插入顺序),你可以很轻易的置换为HashMap,如果使用Hashtable就没那么容易了。

(5)迭代HashMap采用快速失败机制,而Hashtable不是,所以这是设计的考虑点

ArrayList中的浅拷贝与深拷贝

浅拷贝:被复制对象的所有变量都含有与原来的对象相同的值,而所有的对其他对象的引用仍然指向原来的对象。换言之,浅复制仅仅复制所考虑的对象,而不复制它所引用的对象。

深拷贝:被复制对象的所有变量都含有与原来的对象相同的值,除去那些引用其他对象的变量。那些引用其他对象的变量将指向被复制过的新对象,而不再是原有的那些被引用的对象。换言之,深复制把要复制的对象所引用的对象都复制了一遍.(eg: 1、直接赋值(字符串外都属于浅拷贝) 2、使用构造函数(深拷贝) 3、使用clone()方法(深拷贝) )

ArrayList中为何加transient关键字?

transient是Java语言的关键字,变量修饰符,如果用transient声明一个实例变量,当对象存储时,它的值不需要维持。这里的对象存储是指,Java的serialization提供的一种持久化对象实例的机制。当一个对象被序列化的时候,transient型变量的值不包括在序列化的表示中,然而非transient型的变量是被包括进去的。使用情况是:当持久化对象时,可能有一个特殊的对象数据成员,我们不想用serialization机制来保存它。为了在一个特定对象的一个域上关闭serialization,可以在这个域前加上关键字transient。

Java中的泛型是什么 ? 使用泛型的好处是什么?

泛型的本质是参数化类型,也就是说所操作的数据类型被指定为一个参数。这种参数类型可以用在类、接口和方法的创建中,分别称为泛型类、泛型接口、泛型方法。 泛型的好处是在编译的时候检查类型安全,并且所有的强制转换都是自动和隐式的,提高代码的重用率。

Java的泛型是如何工作的 ? 什么是类型擦除?

Java中的泛型基本上都是在编译器这个层次来实现的。在生成的Java字节码中是不包含泛型中的类型信息的。使用泛型的时候加上的类型参数,会在编译器在编译的时候去掉。这个过程就称为类型擦除。

请举例说明static和泛型的冲突所在

泛型类确定T的类型实在运行是时期,而static在编译时期已经存在。