http://www.cnblogs.com/tiandi/p/10641773.html
1、概念说明
区别:数组固定长度的,集合,数组的长度是可以变化的。
List,继承Collection,可重复、有序的对象
Set,继承Collection,不可重复、无序的对象
Map,键值对,提供key到value的映射。key无序、唯一;value无序,可重复
2、集合类结构图
3、集合特性比较
线程安全的效率都比较低,Vector,已被淘汰,可使用ArrayList替代。Hashtable,已被淘汰,可使用HashMap替代,如果是高并发的线程安全的实现,推荐使用ConcurrentHashMap。
4、接口和方法
Collection的常见方法:
(1)添加
boolean add(E o); (6)修改:set(index,elementt) (7)查询:get(index),indexof(obj)
(2)删除
boolean remove(Object o);
boolean removeAll(Collection extends E> c)
void clear();
(3)判断
a.判断集合中是否有元素:boolean isEmpty();
b.判断集合中是否包含某个元素:boolean contains(Object o);
c.判断集合中是否包含某些元素:boolean contains(Collection> c);
(4)获取
a.获取集合中元素个数:int size();
b.遍历集合中所有元素(迭代器):Iterator iterator();
c.判断两个集合中是否存在相同的元素并保留两个集合中相同的元素删除不同的元素:boolean retainAll(Collection> c);
(5)其他
将集合中元素转为数组: Ojbect[] toArray();
Map的接口方法:1、增加:put(key,value),putall(map) 2、删除:clear(),remove(key)3、判断:isEmpty(),containValue(),containsKey(), 4、查询:get(key),size(),entrySet(),keySet()
5、集合遍历
list遍历
import java.util.*;
public class Test{
public static void main(String[] args) {
List list=new ArrayList();
list.add("Hello");
list.add("World");
list.add("HAHAHAHA");
//第一种遍历方法使用foreach遍历List
for (String str : list) { //也可以改写for(int i=0;i
System.out.println(str);
}
//第二种遍历,把链表变为数组相关的内容进行遍历
String[] strArray=new String[list.size()];
list.toArray(strArray);
for(int i=0;i
{
System.out.println(strArray[i]);
}
//第三种遍历 使用迭代器进行相关遍历
Iterator ite=list.iterator();
while(ite.hasNext())//判断下一个元素之后有值
{
System.out.println(ite.next());
}
}
}
map遍历
import java.util.*;
public class Test{
public static void main(String[] args) {
Map map = new HashMap();
map.put("1", "value1");
map.put("2", "value2");
map.put("3", "value3");
//第一种:普遍使用,二次取值
System.out.println("通过Map.keySet遍历key和value:");
for (String key : map.keySet()) {
System.out.println("key= "+ key + " and value= " + map.get(key));
}
//第二种
System.out.println("通过Map.entrySet使用iterator遍历key和value:");
Iterator> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = it.next();
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
//第三种:推荐,尤其是容量大时
System.out.println("通过Map.entrySet遍历key和value");
for (Map.Entry entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
//第四种
System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
for (String v : map.values()) {
System.out.println("value= " + v);
}
}
}
6、数组使用的几个例子
数组和集合:
1.数组第一种定义方式
int[] counts = {1,2,3,4,5};
2.数组第二种定义方式(先初始化,后赋值)
int[] numbers = new int[3];
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[0] = 1000;//在索引范围以内可以更改
3.数组创建第三种方式
int[] nums = new int[] {1,2,3};
//修改
nums[0] = 1000;
转载于:https://www.cnblogs.com/tiandi/p/10641773.html
标签:map,遍历,java,数组,System,value,println,key,集合
来源: https://blog.csdn.net/weixin_30650039/article/details/98189324