《Java基础入门第2版》--黑马程序员 课后答案及其详解 第6章 集合

一、填空题

1、Comparator
2、hashNext()、next()
3、键、值
4、ArrayList、LinkedList,HashSet、TreeSet,HashMap、TreeMap
5、forEach(Consumer action)

二、判断题

1、错   2、对   3、对   4、错   5、对

三、选择题

1、BC      2、D      3、C      4、D     5、ABC   

四、简答题

1、为了使程序能方便的存储和操作数目不固定的一组数据,JDK提供了一套类库,这些类都位
于java.util包中,统称为集合。集合框架中常用的接口和类有,List、Set、ArrayList、HashSet、Map、HashMap、TreeMap。

2、List的特点是元素有序、可重复。List接口的主要实现类有ArrayList和LinkedList。Set的特点是元素无序、不可重复。Set接口的主要实现类有HashSet和TreeSet。Map的特点是存储的元素是键(Key)、值(Value)映射关系,元素都是成对出现的。Map接口的主要实现类有HashMap和TreeMap。

3、Collection是一个单例集合接口。它提供了对集合对象进行基本操作的通用方法。Collections是一个工具类。它包含各种有关集合操作的方法。

五、编程题

1.import java.util.*;
public class Test02 {
    
    
	public static void main(String[] args) {
    
    
		HashSet hashSet = new HashSet();
		Person p1 = new Person("Jack",25);
		Person p2 = new Person("Rose",23);
		Person p3 = new Person("Jack",27);
		hashSet.add(p1);
		hashSet.add(p2);
		hashSet.add(p3);
		for(Object obj:hashSet){
    
    
			Person p=(Person)obj;
			System.out.println(p.name+":"+p.age);
		}
	}
}
class Person{
    
    
	String name;
	int age;
	public Person(String name, int age) {
    
    
		super();
		this.name = name;
		this.age = age;
	}
	public int hashCode() {
    
    
	   return name.hashCode();
	}
	public boolean equals(Object obj) {
    
    
		if (this == obj)
			return true;
		if (obj == null)
return false;
		Person p = (Person) obj;
		return p.name.equals(this.name);
	}
}	
2.import java.util.*;
public class Test03 {
    
    
	public static void main(String[] args) {
    
    
		TreeMap map = new TreeMap(new MyComparator());
		map.put("1", "Lucy");
		map.put("2", "Lucy");
		map.put("3", "John");
		map.put("4", "Smith");
		map.put("5", "Amanda");
		for (Object key : map.keySet()) {
    
    
			System.out.println(key + ":" + map.get(key));
		}
	}
}
class MyComparator implements Comparator {
    
    
	public int compare(Object obj1, Object obj2) {
    
    
		String ele1 = (String) obj1;
		String ele2 = (String) obj2;
		return ele2.compareTo(ele1);
	}
}

六、原题及其解析

暂无。

猜你喜欢

转载自blog.csdn.net/hypertext123/article/details/109297609