一、常用集合类的继承关系:
Collection是什么,先看下源码,
public interface Collection<E> extends Iterable<E>
Iterable中含有迭代器,故而Set和List的实现类都可以使用迭代来遍历集合中的元素。
如何用迭代器来遍历集合中的元素:
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = (String) it.next();
System.out.println(s);
}
二、List、Set、Map的区别
1、List集合中元素允许重复,各元素的顺序就是对象插入的顺序;
2、Set集合中的对象不按特定的方式排序,只是简单地把对象加入集合中,但Set集合中不能包含重复对象;
public class TreeSet<E> extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, java.io.Serializable
public interface NavigableSet<E> extends SortedSet<E>
TreeSet实现了SortSet接口,因此TreeSet中的元素是递增排序。
TreeSet中不能有null元素,HashSet中可以有null元素。
TreeSet中添加null,运行时会报异常。
HashSet中可以添加null
3、Map(key, value)中的key其实相当于一个Set集合,Map中不能包含相同的key;
public interface Map<K,V>