java学习笔记:集合

来源:互联网 发布:mac版绘画软件 编辑:程序博客网 时间:2024/04/30 00:40

数组与集合遍历:
通用:
1)增强for :
for (数组或集合类型 i:数组或集合名){操作 i;}
注意:i是定义的一个局部变量,本身不会对数组或集合造成影响
2)普通for、while循环:直接操作的数组或集合元素本身,所以循环体内部操作会对数组或者集合造成影响

集合特有:Iterator迭代器
Iterator iter = 集合名.iterator();
while(iter.hasNext()){
System.out.println(iter.next());//操作iter,这里以输出为例
}

—集合

——Collection接口
有序、无序、重复性:针对元素或者对象的地址而非实际的值进行的判断(hashCode()方法)
————-List接口(有序、允许重复)
—————–ArrayList接口:基于数组的数据组织(常用)方式
—————–LinkedList接口:基于链表的数据组织方式
—————–vector接口:线程安全
注意通常需要重写元素或对象所在类的equals()方法

————-Set接口(无序、不允许重复)
—————–HashSet接口
—————–LinkedHashSet接口
—————–TreeSet接口:只能存储同类型的元素或对象;可按指定的顺序遍历,如String、包装类等默认按从小到大的顺序遍历;当向TreeSet中添加自定义类的对象时,有两种排序方法:(1)自然排序(2)定制排序
(1)自然排序:要求自定义类实现Comparable接口并重写compareTo()方法;
(2)定制排序:要求创建实现了Comparator接口的类对象,并将该类对象作实参传入TreeSet对象中

——Map接口(键-值对的存储)
注意通常需要重写元素或对象所在类的equals()方法以及hashCode()方法
Map的遍历方法:
public void testMap(){
HashMap map = new HashMap();
map.put(“123”, “CT”);
map.put(“345”, “CTCT”);
map.put(“456”, “CTCTCT”);
map.put(“567”, “CTCTCTCTCT”);
map.put(“678”, “CTCTCTCTCTCTCT”);
//通过键—set
for(Object obj:map.keySet()){
System.out.print(obj);
System.out.print(“——>”);
System.out.println(map.get(obj));
}
//通过值—Collection
Collection col = map.values();
Iterator it = col.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
//通过键、迭代器—Collection、Iterator
Collection col1 = map.keySet();
Iterator it1 = col1.iterator();
while(it1.hasNext()){
Object obj = it1.next();
System.out.println(obj);
System.out.print(“——>”);
System.out.println(map.get(obj));
}
//通过键值对、迭代器、增强for循环—Set、Map.Entry
Set coll3 = map.entrySet();
for( Object obj:coll3){
Map.Entry en = (Map.Entry)obj;
System.out.println(en.getKey());
System.out.print(“——>”);
System.out.println(en.getValue());
}
//通过键值对、迭代器、while循环—Set、Map.Entry、Iterator
Collection coll4 = map.entrySet();
Iterator it4 = coll4.iterator();
while( it4.hasNext()){
Map.Entry en1 = (Map.Entry)it4.next();
System.out.println(en1.getKey());
System.out.print(“——>”);
System.out.println(en1.getValue());
}

}
0 0
原创粉丝点击