java中的集合Collection分为List,Set和Map三种:
List有 ArrayList,LinkedList和Vector三种,Set分为HashSet和TreeSet;Map分为HashSet和TreeMap.
ArrayList和Vector是基于数组实现的,LinkedList是基于链表实现的;数组和链表的主要区别是数组通过索引进行各种操作,而链表则是根据各个元素前仆后继进行链接的,在对List集合进行遍历时可以采用多种方法,比如for,toArray,Iterator和ListIterator方法;HashSet和HashMap是基于哈希表进行操作的,而TreeSet和TreeMap是基于二叉树进行操作的。而map和Set可以使用Iterator和entrySet方法对所有元素进行输出。
例1:
//新建hashset集合
HashSet<String> ss =new HashSet<String>();
//使用add方法,向集合中添加元素
ss.add("asd");
ss.add("qwe");
ss.add("zxc");
//新建父类,接受遍历的结果
Object[] ssString= ss.toArray();
//循环遍历输出数组中的值
for(int i=0;i<ssString.length;i++)
{
System.out.println(ssString[i]);
}
//使用迭代器
Iterator<String> io =ss.iterator();
//通过判断是否存在下一个元素,存在则输出,不存在则结束循环
while(io.hasNext())
{
System.out.println(io.next());
}
//新建Person 集合
TreeSet<Person> ps=new TreeSet<Person>();
//存放数据到集合中
ps.add(new Person("asd",22));
ps.add(new Person("zxc",23));
//使用迭代器输出集合
Iterator<Person> io1 =ps.iterator();
while(io1.hasNext())
{
System.out.println(io1.next());
}
//输出:
asd
zxc
qwe
asd
zxc
qwe
年龄:23姓名:zxc
年龄:22姓名:asd
例2:
TreeMap<String, String> tm=new TreeMap<String,String>();
//添加数据
tm.put("001", "zz");
tm.put("002", "zzz");
tm.put("003", "zzzz");
//建立set关系集合获取所有的set关系
Set<Map.Entry<String, String>> result=tm.entrySet();
//使用迭代器输出新建集合中所有元素
Iterator<Entry<String, String>> it1=result.iterator();
while(it1.hasNext())
{
Entry<String, String> re=it1.next();
System.out.println(re.getKey());
System.out.println(re.getValue());
}
//通过迭代器获取键
Iterator<String> io1=tm.keySet().iterator();
while(io1.hasNext())
{
Object o1=io1.next();
//通过键获取值
System.out.println(o1+"="+tm.get(o1));
}
//建立string-person Map
TreeMap<String, Person> tm1=new TreeMap<String,Person>();
//输入数据
Person p1=new Person("zz",22);
Person p2=new Person("xx",21);
Person p3=new Person("cc",25);
tm1.put("003", p1);
tm1.put("001", p2);
tm1.put("002", p2);
tm1.put("002", p3);
//使用迭代器获取键
Iterator<String> io2=tm.keySet().iterator();
while(io2.hasNext())
{
Object o2=io2.next();
//通过键获取值
System.out.println(o2+"="+tm1.get(o2));
}
//输出:
001
zz
002
zzz
003
zzzz
001=zz
002=zzz
003=zzzz
001=年龄:21姓名:xx
002=年龄:25姓名:cc
003=年龄:22姓名:zz