集合概述:

在编程时,常常需要存放多个数据,可以用数组来保存多个对象,但数组长度不好变化,一旦初始化数组时就指定了数组的长度,这个数组长度就是不可改变的,如果需要保存数量变化的数据时,数组就显得比较无能为力了;而且数组无法保存具有映射关系的数据,例如成绩表:数学-80,语文-90,英语-100,这种数组看上去像两个数组,但其实这个两个数据有一定的关系。

为了保存数量不确定的数组,以及保存像成绩表这样的具有映射关系的数据时,Java提供了新的集合类,集合主要负责保存其他数据,因此集合类也被称为容器,所有集合类位于java.util包下。

集合类和数组不一样,数组元素既可以是基本类型的值,也可以是对象(其实是对象引用的变量);而集合只能保存对象(也是对象引用的变量)。

Java集合类主要是由两个接口派生而出:Collection和Map,Collection和Map是Java集合框架的根接口,这两个接口与也包含了一些子接口或实现类


小马哥java 小马哥java训练营_小马哥java


其中Collection里面的集合:Set与List分别代表无序集合与有序集合。

而Map实现类是用于保存具有映射关系的数据。

2Coleection接

Collection接口是List与Map接口的父类,该接口里定义的方法即可用于操作Set集合也可操作List集合,定义如下几种方法“:

 boolean

add(E           确保此 collection 包含指定的元素(可选操作)。

 boolean

addAll(Collection<? extendsE> c)

          将指定 collection 中的所有元素都添加到此 collection 中(可选操作)。

 void

clear()

          移除此 collection 中的所有元素(可选操作)。

 boolean

contains(Object           如果此 collection 包含指定的元素,则返回 true。

 boolean

containsAll(Collection<?> c)           如果此 collection 包含指定 collection 中的所有元素,则返回 true。

 boolean

equals(Object           比较此 collection 与指定对象是否相等。

 int

hashCode()

          返回此 collection 的哈希码值。

 boolean

isEmpty()

          如果此 collection 不包含元素,则返回 true。

 Iterator<E>

iterator()

          返回在此 collection 的元素上进行迭代的迭代器。

 boolean

remove(Object           从此 collection 中移除指定元素的单个实例,如果存在的话(可选操作)。

 boolean

removeAll(Collection<?> c)           移除此 collection 中那些也包含在指定 collection 中的所有元素(可选操作)。

 boolean

retainAll(Collection<?> c)           仅保留此 collection 中那些也包含在指定 collection 的元素(可选操作)。

 int

size()

          返回此 collection 中的元素数。

 Object[]

toArray()

          返回包含此 collection 中所有元素的数组。



toArray(T[] a)

          返回包含此 collection 中所有元素的数组;返回数组的运行时类型与指定数组的运行时类型相同。

<T> T[]


集合的遍历:

可以使用Iterator遍历几何元素,Iterator接口也是Java集合框架的成员,但它与Collection系列、Map系列集合不一样;Collection系列集合、Map系列结合主要用途关于盛放其他对象,而Iterator则主要用于遍历(迭代访问)Collection集合中的元素,Iterator也成为迭代器

public class IteratorTest
{
	public static void main(String[] args)
	{
	//创建集合
	Collection books = new HashSet();
	books.add("1");
	books.add("2");
	//获取book集合对象的迭代器
	Iterator it=book.iterator();
		while(it.hasNext())
		{
		String book=(String)it.next();
		System.out.println(book);	
		}
	}
}

 下面为遍历Map集合的小例子:

import java.util.*;
public class bianli
{
	public static void main(String[] args) 
	{
		String s ="zxc";
		Map<Character,Integer> map=St(s);
		bianli(map);
	}
	
	public static Map<Character,Integer> St(String s)
	{
		char[] ch=s.toCharArray();
		Map<Character,Integer> map=new TreeMap<Character,Integer>();
		int a=0;
		for(int x=0;x<ch.length;x++)
		{
		if(!map.containsKey(ch[x]))
			{
			map.put(ch[x],1);
			}
		else
			{
			a=map.get(ch[x]);
			map.put(ch[x],++a);
			}
		}
		return map;
	}

	public static void bianli(Map<Character,Integer> map)
	{
		Set se=new TreeSet();
			se=map.entrySet();
		Iterator it =se.iterator();
		while(it.hasNext())
		{
			Map.Entry en=(Map.Entry)it.next();
			System.out.println(en.getKey()+" "+en.getValue());
		}
	}
}