Java容器

来源:互联网 发布:万网中文域名 编辑:程序博客网 时间:2024/06/04 19:45

1
Collections提供了一些静态方法基于List的一些算法
void sort(List)
void shuffle(List)
void reverse(List)
void fill(List, Object)
用一个特定对象重写整个List容器
void copy(List des, List src)
int binarySearch(List, object)
对于顺序的List容器,折半查找
3

增强for

eg:

int[] arr = {3, 4. 8};

for(int i : arr) {

}

Generic

Auto-boxing/unboxing

6
Collection接口:
int size()
boolean isEmpty()
void clear()
boolean contains(Object)
boolean add(Object)
boolean remove(Object)
Iterator iterator()
boolean containsAll(Collection)
boolean addAll(Collection)
boolean removeAll(Collection)
boolean retainAll(Collection)
Object[] toArray();
重写equals()方法,要重写hashCode()方法,
当对象做为索引(键),要用到对象的hashCode()方法

Iterator接口:
所有实现Collection接口的
boolean hasNext();
genetic next();
void remove();
遍历
Collection c = new ArrayList();
for(Iterator i=c.iteartor(); c.hasNext();) {
i.remove();
//不能使用c的remove方法
}

Set接口:
Set容器可以和数学中的集合相对应
API提供的容器类有HashSet,TreeSet等

List接口:
ArrayList和LinkedList
Object set(int index, Object e)
Object get(int index)
Object remove(int index)
Object add(int index, Object e)
int indexOf(Object e)
int lastIndexOf(Object e)

Comparable接口:
只有一个方法
int compareTo(Object)
实现了Comparable接口的类通过实现compareTo方法来比较自定义类不同对象的大小

Map接口:
键值对
键,也就是索引不能重复
HashMap和TreeMap
Object put(Object key, Object value)
Object get(Object key)
Object remove(Object key)
boolean containsKey(Object key)
boolean containsValue(Object value)
int size()
boolean isEmpty()
void putAll(Map t)
void clear()

如何选择数据结构:
Array读快改慢
Linked改快读慢
Hash两者之间

泛型:
原因装入集合都被当做Object对待,从而失去自己的实际类型
从集合中取出时需要强制转换,效率低,容易产生错误

for(Iterator<String> i = c.Iterator(); Iterator.hasNext();){}


0 0