浪潮优派培训java笔记:第9章 类集Collections(容器)



第9章 类集Collections(容器)

9.1 概述

类集,又称集合类或容器,用来存放对象。

容器:JavaAPI所提供的一系列类的实例,用于在程序中存放对象。

集合类所在的包:java.util

容器API

Set 接口继承Collection,但不允许重复。

 List 接口继承Collection,允许重复,并引入位置下标。

 Map 接口不继承 Collection。

       如何选择数据结构:

ArrayList读块改慢(类似数组)

LinkedList改快读慢(类似链表)

HashSet两者之间

9.1  Collection接口

  Collection接口:是一组允许重复的对象。

  Collection接口定义了存取一组对象的方法,其子接口Set和List分别定义了存储方式。

        Set中的数据对象没有顺序且不可以重复;

        List中的数据对象有顺序且可以重复;

 Collection接口的方法摘要

 boolean add(Object element)  // 添加元素。

 boolean addAll(Collection c)  //将指定 collection 中的所有元素都添加到此 collection 中。

 void clear() // 移除此collection 中的所有元素。

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

 boolean containsAll(Collectionc) // 如果此 collection 包含指定 collection 中的所有元素,则返回 true。

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

 boolean isEmpty() // 如果此collection 不包含元素,则返回 true。

 Iterator<E> iterator() // 返回在此 collection 的元素上进行迭代的迭代器。

 boolean remove(Object element) // 从此 collection 中移除指定元素的单个实例,如果存在的话。

 boolean removeAll(Collection c) // 移除此 collection 中那些也包含在指定 collection 中的所有元素。

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

 int size()//返回此 collection 中的元素数。

 Object[] toArray()//返回包含此collection 中所有元素的数组。

<T>T[]  toArray(T[] a) // 返回包含此collection 中所有元素的数组;返回数组的运行时类型与指定数组的运行时类型相同。

【程序示例】:

public class Name {

    private String firstName;

    private String lastName;

    public Name(StringfirstName, String lastName) {

       this.firstName = firstName;

       this.lastName = lastName;

    }

    public StringgetFirstName() {

       return firstName;

    }

    public StringgetLastName() {

       return lastName;

    }

    public String toString(){

       return firstName + " " + lastName;

    }

}

 

import java.util.*;

public class ArrayListDemo {

    public static void main(String[]args) {

       Collection c= new ArrayList();

       c.add("hello");

       c.add(new Name("f1","l1"));

       c.add(100);

       System.out.println(c.size());

       System.out.println(c); //调用toString方法

    }

}

【运行结果】:3

[hello, f1 l1, 100]

9.1.1  List接口

       List接口:(有顺序、可重复)

List接口是Collection的子接口,实现List接口的容器类中的元素是有顺序,而且可以重复。

List容器中的元素都对应一个整数型的序号记载其在容器中的位置,可以根据序号存取容器中的元素。

实现类:ArrayList和LinkedList

       ArrayList(重点):(类似数组)

【特点】可以添加重复值、可以添加null、元素下标和添加的顺序相符合、允许通过下标访问元素 

【常用方法】add(),addAll(),remove(), get(int), set(int ,Object);

【程序示例】

    public static void main(String[] args) {

       List list = new ArrayList();

       list.add("120");

       list.add(10); // 自动装箱

       list.add("hello");

       System.out.println("list:" + list);//list:[120, 10,hello]

       List list2 = new ArrayList();

       list2.add("hello");

       list2.add(1);

       System.out.println("list2:" + list2);//list2:[hello,1]

       list.addAll(list2);// 添加一个集合类

       System.out.println("list:" + list);//list:[120, 10,hello, hello, 1]

       list.add(20);//元素下标和添加的顺序相符合,所以20会被放在最后

       System.out.println("list:" + list);//list:[120, 10,hello, hello, 1, 20]

       list.remove(0);

       System.out.println("list:" + list);//list:[10,hello, hello, 1, 20]

       /**

        * ArrayList允许通过下标访问集合元素

        */

       System.out.println("下标为2的元素:" + list.get(2));//下标为2的元素:hello

       list.set(1, "world");//把下标为1的元素设为"world"

       System.out.println("list:" + list);//list:[10,world, hello, 1, 20]

       Iteratori = list.iterator();

       while (i.hasNext()){

           //Object o =i.next();

           System.out.print(i.next()+" ");

       }

       System.out.println();

       list.add(null);

       System.out.println("list:" + list);

//list:[10, world, hello, 1, 20, null]

}

 

      LinkedList:(类似链表)

【特点】:1.添加对列表的头部和尾部进行操作的方法  2.可以添加null  3.可以添加重复值

【程序示例】

    public static void main(String[] args) {

       List list = new LinkedList();

       list.add("test");

       list.add("ynz");

       list.add(100);

       System.out.println(list);//[test,ynz, 100]

       System.out.println(list.get(1));//ynz

       list.set(2, "java");//把下标为2的元素设为"java"

       System.out.println(list);//[test,ynz, java]

 

       LinkedList list2 = new LinkedList();

       list2.add("hello");

       list2.add(20);

       list2.addFirst("first");//在开头位置加入"first"

       list2.addLast("last");//在开头位置加入"last"

       System.out.println(list2);//[first,hello, 20, last]

 

       list.addAll(list2);

       System.out.println(list);//[test,ynz, java, first, hello, 20, last]

 

       list2.removeFirst();//删除第一个元素

       list2.removeLast();//删除第一个元素

       System.out.println(list2);//[hello,20]

 

       // peek():返回集合中第一个元素,且不删除

       System.out.println(list2.peek());//hello

       System.out.println(list2);//[hello,20]

 

       // poll():返回集合中第一个元素,且删除此元素

       System.out.println(list2.poll());//hello

       System.out.println(list2);//[20]

 

       list2.add(null);

       list2.add(20);

       System.out.println(list2);//[20,null, 20]

}

9.1.2  Set接口

       Set接口:(有顺序、不可以重复)

Set接口是Collection的子接口,Set接口没有提供额外的方法,但实现Set接口的容器类中的元素是没有顺序的,而且不可以重复。

 实现类:HashSet和TreeSet

       HashSet:

【特点】1.可以添加null 2.不允许重复的元素  

【常用方法】add(),addAll(), iterator(), remove(),contains()

【程序示例】

    public static void main(String[] args) {

       Set set1 = new HashSet();

       set1.add(100);

       set1.add("hello");

       set1.add(3.5);

       System.out.println("set1:" + set1);// set1:[100,hello, 3.5]

       set1.add("hello"); // 相同的元素不会被加入

       set1.add(null);

       System.out.println("set1:" + set1);// set1:[100,hello, 3.5, null]

       Set set2 = new HashSet();

       set2.add(1);

       set2.add("hello");

       System.out.println("set2:" + set2);// set2:[hello,1]

       set1.addAll(set2); // 添加一个集合类

       System.out.println("set1:" + set1);// set1:[100,hello, 1, 3.5, null]

       set1.remove(3.5); // 删除某个元素

       System.out.println("set1:" + set1);// set1:[100,hello, 1, null]

       set1.removeAll(set2); // 删除一个集合类

       System.out.println("set1:" + set1);// set1:[100,null]

       /**

        * 通过迭代器来遍历Set

        */   

       Iterator i = set1.iterator(); // 创建迭代器

       System.out.print("set1的元素:");

       while (i.hasNext()) {

           System.out.print(i.next() + " ");

       }

       System.out.println();

       boolean bool = set1.contains(100);

       System.out.println(bool);// true

       set1.clear(); // 删除集合类的所有元素

       System.out.println("set1:" + set1);//set1:[]

    }

 

      TreeSet:

【特点】1.不允许重复值 2.可以对元素进行排序(升序),元素类型要一致 3.不允许添加null值

【程序示例】

    public static void main(String[] args) {

       Set set = new TreeSet();

       set.add(100);

       set.add(120);

       System.out.println(set);//[100,120]

       TreeSet set2 = new TreeSet();

       set2.add(10);

       set2.add(120);

       set.addAll(set2);

       System.out.println(set);//[10,100, 120]

       set.add(5);

       System.out.println(set);//[5, 10,100, 120]

       set.add(20);

       System.out.println(set);//[5, 10,20, 100, 120]

       // set.add(null); 不能添加null

       Iterator i = set.iterator();

       while (i.hasNext()) {

           System.out.print(i.next()+"");

       }

       System.out.println();

       System.out.println("set中元素的个数:" + set.size());//set中元素的个数:5

    }

 

历史类(JDK1.0)(了解)

ArrayList:Vector

LinkedList:Stack

 

9.2  Map接口

      Map接口

Map接口定义了存储“键(key)-值(value)映射对”的方法。

Map中存放的是key=value对(键-值对),可以通过键寻找值。(key和value之间用=连接)

Map类中存储的键-值对通过键(key)来标识,所以key不能重复,但值可以重复。

实现类:HashMap和TreeMap

       HashMap :(重点)由哈希表实现

1.存放键值对 2.键不能重复,值可以重复  3.键和值都可以为null

遍历map的两种方式:

(1)通过keySet()获取所有的键,通过键取值:get(key)

(2)通过entrySet()获取所有的Map.Entry<K,V>类型的数据,通过每个Map.Entry的getKey,getValue方法来获取键和值

【程序示例】

    public static void main(String[] args) {

       Map map = new HashMap();

       map.put(1, 2000);

       map.put(2, 4000);

       map.put(3, 2500);

       map.put("java", "1578");

       map.put(4, "good");

       System.out.println(map);//{java=1578,2=4000, 4=good,1=2000, 3=2500}

       map.put(2, 5000);  //会覆盖原有的value,因为key不可以重复

       System.out.println(map);//{java=1578,2=5000, 4=good,1=2000, 3=2500}

       map.put(5, 2000);  // value可以重复

       System.out.println(map);

//{java=1578, 2=5000, 4=good, 1=2000, 3=2500, 5=2000}

       map.put(null, null); //可以添加null

       System.out.println(map);

//{java=1578, 2=5000, 4=good, 1=2000, null=null, 3=2500,5=2000}

       /*

        * 通过key找value的方法: value get(key);遍历map

        */

       Set keys = map.keySet();// keySet():返回map中所有键的集合

       Iterator i = keys.iterator();

       while (i.hasNext()) {

           Object key = i.next();

           System.out.println("value:" + map.get(key));

       }

【遍历map的两种方法】

    public static void main(String[] args) {

       Map<Integer, String> map = new HashMap<Integer, String>();

       map.put(1, "world");

       map.put(2, "String");

       map.put(3, "hello");

       /**

        * 遍历map的方法(一) keySet(); 找到所有的键

        */

       Set<Integer> set = map.keySet();

       Iterator<Integer> i = set.iterator();

       while (i.hasNext()) {

           Integer key = i.next();

           System.out.println(map.get(key));

       }

       /*

        * 遍历map的方法(二)Set<Map.Entry<k,V>> entrySet()

        *                                   返回此映射中包含的映射关系的 set 视图。

        */

       Set<Map.Entry<Integer, String>> set2 =map.entrySet();

       //Iterator<Map.Entry<Integer, String>> i2=set2.iterator();也可实现

       for (Map.Entry<Integer, String> entry : set2) {

           Integer key = entry.getKey();

           String value = entry.getValue();

           System.out.println(key + " =" + value);

       }

    }

      TreeMap:由二叉树实现

1.存放键值对 2.键不能重复,值可以重复 3.按键的大小进行自动排序(升序) 4.键不能为null,值可以为null

【程序示例】

    public static void main(String[] args) {     

       Map<String,String> map=new TreeMap<String,String>();   

       map.put("001", "lilei");

       map.put("002", "hanmeimei");

       map.put("hello", "nihao");

       map.put("good", "morning");

       map.put("aaa", "test");    

       map.put("good", "test");

       map.put("003",null);

       System.out.println(map);

//{001=lilei, 002=hanmeimei, 003=null, aaa=test,good=test, hello=nihao}

}

 

历史集合类:(了解)

HashMap:HashTable

TreeMap:Properties

 

9.3  Iterator接口

       Iterator接口: (重点)

主要用于遍历集合类中的元素;

所有实现了Collection接口的容器类都有一个iterator()方法用以返回一个实现了Iterator接口的对象。

Iterator对象称作迭代器,用以方便的实现对容器内元素的遍历操作。

Iterator接口定义了如下方法:

        boolean  hasNext(); //判断容器内是否还有元素

        Object  next(); //返回容器内的下一个元素

        void  remove(); //


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值