#Java学习#(六)容器

其他JAVA学习的内容见:目录

概念与框架

  • 容器类:Java类库中提供的用于管理对象集合的类
    在这里插入图片描述
  • Collection
    • 列表(List):按照一定次序(对象进入的顺序)排列的对象集,对象之间有次序关系,对象可以重复。
    • 集合(Set):对象唯一,不会重复;元素没有顺序。
    • 队列(Queue):根据排队规则确定对象的顺序。
  • Map(映射表)
    • 一群成对的对象集,这些对象各自保持着“键-值”(key-value)对应关系。
    • 允许使用一个对象来查找另一个对象。

Collection&List

  • Collection接口
    int size();
    boolean isEmpty();
    boolean contains(Object o);
    Iterator<E> iterator();
    Object[] toArray();
    boolean add(E o);
    boolean remove(Object o);
    boolean containsAll(Collection<?> c);
    boolean addAll(Collection<? extends E> c);
    boolean removeAll(Collection<?> c);
    boolean retainAll(Collection<?> c);
    void clear();
    boolean equals(Object o);
  • List接口
    • Collection接口的子接口
    • 特点:实现该接口的类中的元素有顺序,可以重复。
    • List容器中的元素都有一个对应的整数型的序号,用以记录元素在容器中的位置,可以根据序号取元素。
    • 主要实现类:ArrayListLinkedList
   Object get(int index);
   Object set(int index, Object element);
   void add(int index,Object element);
   Object remove(int index);
   int indexOf(Object o);
   int lastIndexOf(Object o);
  • 实例:泛型
List<String> list = new LinkedList<String>();
for(int i=0;i<=5;i++){
	list.add("a"+i);
}
System.out.println(list);
list.add(3,"b");
System.out.println(list);
list.set(6,"c");
System.out.println(list);
System.out.println(list.get(2));
  • Vector(不建议使用)
    • List接口的实现类。
    • 特点:跟ArrayList一样,都是可变长的对象数组。
    • 与ArrayList区别
      • Vector是线程安全的,是可以同步的,运行效率低;
      • ArrayList不同步,适合於单线程环境中。
    • 常用方法(List中未定义)
public Object elementAt(int index)
public void addElement(Object obj)
public void removeElementAt(int index)
public void insertElementAt(E obj, int index)
public boolean removeElement(Object obj)
public void removeAllElements()

栈与队列

  • Stack(栈)
  • extend Vector
  • 特点:后进先出的对象堆栈
  • 主要方法:
    • public Object push(E item)
    • public Object pop()
    • public Object peek()
    • public boolean empty()
    • public int search(Object o)
  • 实例
Stack s = new Stack();
s.push("hello");
s.push(new Date());
s.push(100);
s.push(3.14);

System.out.println("弹栈前:size=" + s.size());
System.out.println(s.pop());
System.out.println("弹栈后:size=" + s.size());
System.out.println(s.peek());
System.out.println("peek操作后:size=" + s.size());
while(!s.isEmpty()){
      System.out.println(s.pop());
}
//弹栈前:size=4
//3.14
//弹栈后:size=3
//100
//peek操作后:size=3
//100
//Fri Dec 05 17:09:20 CST 2008
//hello
  • Queue(队列)
    • 队列:一种先进先出(FIFO)的容器,从容器的一端放入对象,从另一端取出对象,并且放入和取出的顺序相同。
    • 主要方法
      • offer():(入队)如果可能,将指定的元素插入此队列。
      • peek()element():在不移除的情况下返回队头。peek方法在队列为空时返回null,element方法在队列为空时抛出异常。
      • poll()remove():移除并返回队头(出队)。poll方法在队列为空时返回nullremove方法在队头为空时抛出异常。
    • 主要实现类:LinkedList
Queue queue = new LinkedList();
queue.offer("Hello");
queue.offer("World!");
queue.offer("你好!");
System.out.println(queue.size());
String str;
while ((str = (String)queue.poll()) != null) {
	System.out.println(str);
}
System.out.println(queue.size());

集合set

  • Collection接口的子接口,未提供额外的方法。
  • 实际上Set就是Collection,只是行为不同(继承与多态思想的典型应用:表现不同的行为)。
  • 实现Set接口类的特点:元素无顺序,不重复。
  • JDK API中Set的实现类:HashSetTreeSetLinkedHashSet

HashSet

  • HashSet
    • HashSet中使用hashCodeequals方法判断是否相同,为了提高效率,先调用hashCode方法(返回hashcode值),hashCode相同的才调用equals方法判断是否相同
    • 如果一个类要实现hashCode必须和equals方法一块实现hashCode方法和equals方法返回值的关系满足:
      • equals()true的两个对象,hashcode()返回值一定相等;
      • equals()不为true的两个对象,它们的hashCode()不一定相等。即,equals()不为true的两个对象,hashCode()有可能相等。(哈希码在生成的时候可能产生冲突)。
      • hashCode()不等的两个对象,equals()不为truehashCode()相等,equals()可能为true ,也可能不为true
    • hashCode方法的重写:返回一个result

TreeSet

  • 实现了Set接口,是Set的一个变体,是一个实现了排序功能的集合(类似于“插入排序”)。
  • 工作原理:将对象元素添加到TreeSet中时会自动按照某种比较规则,将其插入到有序的对象序列中,以保证TreeSet集合元素组成的对象序列时刻按照“升序”排列;如果没指定排序规则,则会按照对象的hash编码来排序

字典Map

  • 实现Map接口的类:存储“键-值”对。
  • 主要实现类:HashMapTreeMap
  • Map中“键值对”通过键标示,键要唯一,不重复
    • 重复:equalstruehashCode相等)

HashMap

  • 基于哈希表实现了映射集合结构。
  • 特点:不保证其中元素的先后顺序,并且允许使用“null”键和“null”值
	public static void main(String args[]) {
		Map m1 = new HashMap();
		Map m2 = new TreeMap();
		m1.put("one", new Integer(1));
		m1.put("two", new Integer(2));
		m1.put("three", new Integer(3));
		m2.put("A", new Integer(1));
		m2.put("B", new Integer(2));
		System.out.println(m1.size());//3
		System.out.println(m1.containsKey("one"));//true
		System.out.println(m2.containsValue(new Integer(1)));/true
		if (m1.containsKey("two")) {
			int i = ((Integer) m1.get("two")).intValue();
			System.out.println(i);//2
		}
		Map m3 = new HashMap(m1);
		m3.putAll(m2);
		System.out.println(m3);//{two=2, A=1, B=2, one=1, three=3}
	}

Hashtable

  • 特点:实现Map接口,与HashMap作用基本一样。
  • HashtableHashMap的用法、格式完全相同。
  • HashMap的区别:
    • Hashtable是同步的,线程安全的,效率低一点;HashMap不同步,效率较高,适合於单线程环境;
    • Hashtable的键值都不能为null

Properties

  • public class Properties extends Hashtable<Object,Object>
  • 作用:处理属性文件时方便,把Map对象和属性文件关联起来
    • 可以把Map对象中的key-value对写入到属性文件;
    • 可以把属性文件中的“属性名=属性值”加载到Map对象中。
  • 说明:keyvalue都是String类型
Properties props = new Properties();
// 向Properties中增加属性
props.setProperty("username" , "admin");
props.setProperty("password" , "123456");
// 将Properties中的key-value对保存到a.ini文件中
props.store(new FileOutputStream("e:/gar/a.ini"),"用户名密码表");
// 新建一个Properties对象
Properties props2 = new Properties();
props2.load(new FileInputStream("e:/gar/a.ini") ); 
String username = props2.getProperty("username");
String pwd = props2.getProperty("password");
System.out.println("用户名是:"+username+",密码是:"+pwd);//用户名是:admin,密码是:123456

迭代器

  • 容器的遍历:必须根据容器的确切类型进行编码。
  • 迭代器:以统一的方式遍历容器中的对象,程序员不必知道该容器的底层结构。

Iterator接口

  • 作用:以统一的方式对各种集合元素进行遍历、迭代。
  • 实现Collection接口的容器类都有一个iterator方法。
    • 返回一个实现了Iterator接口的对象。
  • Iterator中的方法
    • boolean hasnext( )
    • object next()
    • void remove( )
  • 实例(只能前移)
 Collection c = new HashSet();
 c.add(new Student(1,"Tom",60));
 c.add(new Student(2,"Peter",70));
 c.add(new Student(3,"Bob",80));
 Iterator i = c.iterator();
 while(i.hasNext()){
       Student s = (Student)i.next();//没有使用泛型,所以要加强制类型转换
       System.out.println(s.getName());
 }
  • 缺点:
    • 对于数组:不能方便的访问数组下标。
    • 对于Collection,不能方便的删除元素。
  • 说明:
    • 所有的Collection都可以使用foreach语法遍历。
    • 对容器只是向前遍历、不修改容器本身时使用。
    • 除了简单遍历,不要使用增强的for循环。

ListIterator接口

  • Iterator的子类型,功能更强大,只能用于各种List的访问。
  • 特点:可以双向移动。
  • 创建方法(来源于List
    • listIterator():产生一个指向List开始处的ListIterator
    • listIterator(n):创建一个开始指向列表索引为n的元素处的listIterator。
  • 实例
List all = new ArrayList();
all.add("hello");
all.add("_");
all.add("world");
ListIterator iter = all.listIterator();
while (iter.hasNext()) {
	String str = (String)iter.next();
	System.out.println(str + " ");
}
while (iter.hasPrevious()) {
	String str = (String)iter.previous();
	System.out.println(str + " ");
}

实用类

  • Collections类
    • java.util.Collections提供了List容器操作的静态方法
    • 常用方法
      • void sort(List list);//对List容器内元素排序
      • void reverse(List list);//对List容器内的对象进行逆序排列
      • void copy(List dest,List src);//把src中List容器内容拷贝到dest List容器
      • int binarySearch(List list, Object key);//对顺序的List容器,用折半查找方法查找指定对象
      • void shuffle(List);//对List容器内的对象进行随机排序
  • Arrays类
    • 定义了多种数组操作方法,实现了对数组元素的排序、填充、转换为列表或字符串形式、增强的检索和深度比较等功能
    • 实例
Integer[ ] a = {3,25,12,79,48};
System.out.println(Arrays.toString(a));//[3, 25, 12, 79, 48]
Arrays.sort(a);
System.out.println(Arrays.toString(a));//[3, 12, 25, 48, 79]
int idx = Arrays.binarySearch(a,25);
System.out.println(idx);//2

List list = Arrays.asList(3,4,5);
System.out.println(list);//[3, 4, 5]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章