栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java 高级7- 类集框架(Collection、List、Set、输出、Map、工具、关系)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 高级7- 类集框架(Collection、List、Set、输出、Map、工具、关系)

1、Collection

Java类集框架中提供了两大核心接口:Collection接口和Map接口,这两个接口是相对独立的。Collection接口是集合单值操作最大的父接口。

boolean add(E e)
添加一个元素。添加成功返回true,如果不允许重复并且已经包含指定的元素。返回false。

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

void clear()
清空掉集合中的所有元素

boolean contains(Object o)
如果集合中包含指定元素那么返回true。

boolean containsAll(Collection c)
如果该集合中包含指定集合中的所有元素的时候返回true。

boolean isEmpty()
如果集合中没有元素返回true。

boolean remove(Object o)
删除集合中的指定的元素。如果存在NULL,也删除。

boolean removeAll(Collection c)
删除当前集合中所有等于指定集合中的元素。

boolean retainAll(Collection c)
仅保留该指定集合中存在的所有元素。其余删除

int size()
返回该集合中元素的个数。如果超过了Integer.MAX_VALUE,那么返回Integer.MAX_VALUE。

Object[] toArray()
这个方法是集合和数组转化的桥梁。

Iterator iterator()
将集合变为Iterator接口输出。


Collection中两个重要的方法add()和iterator(),子接口中都有。

2、List

(1)List接口是collection子接口,对collectio接口进行了进一步扩充,允许保存重复元素。List接口有两个重要的扩充方法:

E get(int index)
根据索引取得保存数据。E set(int index,E element)
修改数据

(2)List有三个子类:ArrayList,Vector,linkedList

ArrayList

public class TestArrayList {
    public static void main(String[] args) {
        List list=new ArrayList();
        list.add("hello");
        //重复元素
        list.add("hello");
        list.add("Java");
        System.out.println("集合大小为:"+list.size()+" 集合是否为空:"+list.isEmpty());
        for (int i=0;i 

List允许保存重复数据。另外,get()方法是List子接口提供的。如果现在操作的是Collection接口,那么对于此时的数据取出只能够将集合变为对象数组操作。如下:

Collection list=new ArrayList();
list.add("hello");
list.add("hello");
list.add("Java");
// 操作以Object为主,有可能需要向下转型,就有可能产生ClassCastException
Object[] objects=list.toArray();
System.out.println(Arrays.toString(objects));

用Collection接口很容易产生ClassCastException异常,因此在开发过程中尽量少用。

linkedList

List list = new linkedList<>() ;
list.add("hello") ;
list.add("hello") ;
list.add("bit") ;
System.out.println(list) ;
list.remove("hello") ;
System.out.println(list) ;

ArrayList和linkedList的区别

ArrayListlinkedList
封装的是数组封装的是链表
复杂度为1linkedList的复杂度为n

Vector

List list = new Vector();
list.add("hello");
list.add("hello");
list.add("Java");
System.out.println(list);

ArrayList和Vector的区别

ArrayListVector
异步处理,性能较高同步处理,性能较低
线程不安全线程安全
支持Iterator、ListIterator、foreach支持Iterator、ListIterator、foreach、Enumeration
3、Set

Set也有两个子接口:HashSet(无序存储)和TreeSet(有序存储)
(1)HashSet子类

 Set set=new HashSet();
 set.add("hello");
 set.add("hello");
 set.add("Java");
 System.out.println(set);
//输出[Iava ,hello]

从输出可以得到是不允许重复且无序的。

(2)TreeSet子类

   Set set=new TreeSet();
   set.add(1);
   set.add(1);
   set.add(2);
   set.add(3);
   set.add(4);
   set.add(5);
   System.out.println(set);

TreeSet同样不允许重复,输出是升序的。
对象判断必须两个方法equals()、hashCode()返回值都相同才判断为相同。

Set与List区别

setlist
不允许重复允许重复
没有对Collection接口进行扩充对Collection接口进行扩充
没有get()方法有get()方法
无序:存储与添加顺序无关,无下标有序:存储与添加顺序相同,可下标访问
4、 输出

(1)Iterator迭代输出
使用List,Set的时候,为了实现对其数据的遍历,我们经常使用到了Iterator

        List list = new ArrayList<>();
        list.add("hello");
        list.add("java");
        Iterator iterator = list.iterator();
        while(iterator.hasNext()){ //循环输出
            if(iterator.next().equals("hello")){
                iterator.remove();//删除当前
            }
            System.out.println(iterator.next()); //java

        }
        System.out.println(list);  //[java]

    }

进行迭代输出时候使用collection的romove方法会导致并发更新异常,需要使用interator的romove方法删除。

(2)ListIterator双向迭代输出

Iterator只能实现由前到后输出,需要双向迭代输出ListIterator,它继承于Iterator接口,只能用于各种List类型的访问。

       List list = new ArrayList<>();
        list.add("hello");
        list.add("java");
        ListIterator iterator = list.listIterator();
        while(iterator.hasNext()){ //前向后输出
            System.out.println(iterator.next()); //java

        }
        while(iterator.hasPrevious()){ //后向前输出
            System.out.println(iterator.previous()); //java
        }

Iterator和ListIterator主要区别

ListIterator有add()方法向List中添加对象,而Iterator不能;都有hasNext()和next()方法向后遍历,但是ListIterator有hasPrevious()和previous()方法,逆向遍历ListIterator可以定位当前的索引位置,nextIndex()和previousIndex()可以实现。Iterator没有此功能。都可删除对象,但是ListIterator可以实现对象的修改,set()方法可以实现。Iierator仅能遍历,不能修改。

(3)Enumeration枚举输出
主要是为了Vector类提供输出服务的。如果想要获取Enumeration的接口对象,就必须依靠Vector类提供的方法。

获取Enumeration:public Enumeration elements();在Enumeration接口中定义有两个操作方法:

判断是否有下一个元素:pubilc boolean hasMoreElements();
获取当前元素;public E nextElement();
package com.iterator.demo;

import java.util.Enumeration;
import java.util.Vector;

public class IteratorDemo {
    public static void main(String[] args) {
        Vector all = new Vector();
        all.add("hello");
        all.add("world");
        all.add("sina");
        all.add("sohu");
        Enumeration enu = all.elements();
        while (enu.hasMoreElements()) {
            String string = enu.nextElement();
            System.out.print(string+"、");//hello、world、sina、sohu、
        }
    }
}

(4)foreach输出

增强for循环。

    public static void main(String[] args) {
    List arr = new ArrayList();
    arr.add("你好");
    arr.add("我好");
    arr.add("大家好");
        //foreach循环
    for(String str : arr){                      //这里的str就是为了获取每次循环的arr中的值
        System.out.println(str);               //就相当于 String str=arr[i]
        }
    }
5、Map

Collection保存是为了输出,Map是为了key的查找;Map中的集合的键不能重复,值可以重复;每个键只能对应一个值;Collection中的集合称为单列集合,Map中的集合称为双列集合。

(1)Map接口中的常用方法

get方法:获取指定键(key)所对应的值(value);

put方法:将指定的键与值对应起来添加到集合中,返回null,若该键已存在,把指定键所对应的值替换成新值并返回旧的值;

remove方法:根据指定的键(key)删除元素,返回被删除元素的值(value);

keySet():将集合中的key转为set集合;

public class MapDemo {
    public static void main(String[] args) {
        //创建Map对象
        Map map = new HashMap();
        //给map中添加元素
        map.put("邓1", "孙1");
        map.put("李2", "范2");
        map.put("刘3", "柳3");
        //获取Map中的所有key
        Set keySet = map.keySet();
        //遍历存放所有key的Set集合
        Iterator it =keySet.iterator();    **
        while(it.hasNext()){                         //利用了Iterator迭代器**
            //得到每一个key
            String key = it.next();
            //通过key获取对应的value
            String value = map.get(key);
            System.out.println(key+"="+value);
        }
    }
}

(2)HashMap子类

遍历顺序是不确定的;最多只允许一条记录的键为null,允许多条记录的值为null;非线程安全。如果需要满足线程安全,可用 Collections的synchronizedMap方法,或者使用ConcurrentHashMap;默认最大保存16个元素;

  // 1-创建 HashMap 对象 Sites
        HashMap Sites = new HashMap();
        // 2-添加键值对
        Sites.put(1, "Google");
        Sites.put(2, "Runoob");
        Sites.put(3, "Taobao");
        Sites.put(4, "Zhihu");
        // 3-输出 key 和 value
        for (Integer i : Sites.keySet()) {
            System.out.println("key: " + i + " value: " + Sites.get(i));
        }
        // 4-返回所有 value 值
        for (String value : Sites.values()) {
            // 输出每一个value
            System.out.print(value + ", ");
        }
        //5-移除
        Sites.remove(4);
        //6-长度
        System.out.println(Sites.size());
        // 7-获取指定key的value
        System.out.println(Sites.get(1));

HashMap由数组+链表组成的,数组是HashMap的主体,链表则是主要为了解决哈希冲突而存在的。阈值小于8为链表,超过8转为红黑树。

(3)linkedHashMap子类
HashMap的子类,为了实现有序,基于链表实现。

  // 1-创建 HashMap 对象 Sites
        HashMap Sites = new linkedHashMap<>();
        // 2-添加键值对
        Sites.put(1, "Google");
        Sites.put(2, "Runoob");
        Sites.put(3, "Taobao");
        Sites.put(4, "Zhihu");
        // 3-输出 key 和 value
        for (Integer i : Sites.keySet()) {
            System.out.println("key: " + i + " value: " + Sites.get(i));
        }
        // 4-返回所有 value 值
        for (String value : Sites.values()) {
            // 输出每一个value
            System.out.print(value + ", ");
        }
        //5-移除
        Sites.remove(4);
        //6-长度
        System.out.println(Sites.size());
        // 7-获取指定key的value
        System.out.println(Sites.get(1));

(4)Hashtable子类
HashMap与Hashtable区别

HashMapHashtable
k-v允许为空k-v不允许为空
异步操作,非线程安全同步操作、线程安全

(5)Map.Entry内部接口
通过集合中每个键值对(Entry)对象,获取键值对(Entry)对象中的键与值

public class MapDemo {
    public static void main(String[] args) {
        //创建Map对象
        Map map = new HashMap();
        //给map中添加元素
        map.put("邓1", "孙1");
        map.put("李2", "范2");
        map.put("刘3", "柳3");
        //获取Map中的所有key与value的对应关系
        Set> entrySet = map.entrySet();
        //遍历Set集合
        Iterator> it =entrySet.iterator();
        while(it.hasNext()){
            //得到每一对对应关系
            Map.Entry entry = it.next();
            //通过每一对对应关系获取对应的key
            String key = entry.getKey();
            //通过每一对对应关系获取对应的value
            String value = entry.getValue();
            System.out.println(key+"="+value);
        }
    }
}

(6)利用Iterator输出Map集合

Map集合不能直接使用迭代器或者foreach进行遍历。但是转成Set之后就可以使用了。

//假设key 为Integer型 value 为String ,具体自行定义
Map map = new HashMap();
// 放入数据
 
map.put(1,"a");
map.put(2,"b");
map.put(3,"c");
//根据key获取对应的value

map.get(1); //获取到对应key=1时的value=a
//遍历方法keyset遍历

Iterator iter = map.keySet().iterator();
 
while (iter.hasNext()) {
 
    int key = iter.next();
 
    String value = map.get(key);
}

(7)自定义Map的key类型

get 查询时候需要使用hashcode查找,自定义类型需要覆写equals与hashcode方法,否则无法查到。HashMap的Hash冲突:为了保证程序正常执行,会将冲突位置的内容转为链表保存。 6、 工具类

(1)Stack栈操作

栈(顶和底):先进后出,是vector的子类,空栈出栈抛出异常;

        Stack strings = new Stack<>();
        //入栈
        strings.push("1");
        strings.push("2");
        //出栈
        System.out.println(strings.pop()); //2
        System.out.println(strings.pop()); //1
        System.out.println(strings.pop()); //无数据,出栈异常,.EmptyStackException
    }

(2)Queue队列

队列(头和尾):先进先出;
linkedList类实现了Queue接口,因此我们可以把linkedList当成Queue来用;

linkedList

       Queue queue = new linkedList<>();
        //添加元素
        //add()和remove()方法在失败的时候会抛出异常(不推荐)
        queue.offer("a");
        queue.offer("X");
        queue.offer("b");
        for(String q : queue){
            System.out.println(q);
        }
        System.out.println("poll=" + queue.poll()); //返回第一个元素,并在队列中删除:a
        System.out.println("element=" + queue.element()); //返回第一个元素:b
        System.out.println("peek=" + queue.peek()); //返回第一个元素:b

执行结果:

a
X
b
poll=a
element=X
peek=X

PriorityQueue
优先队列PriorityQueue是Queue接口的实现,可以对其中元素进行排序;
可以放基本数据类型的包装类(如:Integer,Long等)或自定义的类;
对于基本数据类型的包装器类,优先队列中元素默认排列顺序是升序排列;

       Queue queue = new PriorityQueue<>();
        //添加元素
        //add()和remove()方法在失败的时候会抛出异常(不推荐)
        queue.offer("a");
        queue.offer("X");
        queue.offer("b");
        for(String q : queue){
            System.out.println(q);
        }
        System.out.println("poll=" + queue.poll()); //返回第一个元素,并在队列中删除:a
        System.out.println("element=" + queue.element()); //返回第一个元素:b
        System.out.println("peek=" + queue.peek()); //返回第一个元素:b

执行结果:

X
a
b
poll=X
element=a
peek=a

(3)Properties属性操作
Properties类是Hashtable,只能操作String类型;
它提供了几个主要的方法:

getProperty ( String key),用指定的键搜索属性。也就是通过 key 得到 value。

load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。

setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。调用基类的put方法来设置 键 - 值对。

store ( OutputStream out, String comments),以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。

clear (),清除所有装载的 键 - 值对。

实例:

获取JVM的系统属性

   Properties pps = System.getProperties();

根据key读取value,读取properties的全部信息,写入新的properties信息

//新建一个配置文件(Test.properties)
name=JJ
Weight=4444
Height=3333
//关于Properties类常用的操作
public class TestProperties {
    //根据Key读取Value
    public static String GetValueByKey(String filePath, String key) {
        Properties pps = new Properties();
        try {
            InputStream in = new BufferedInputStream (new FileInputStream(filePath));
            pps.load(in);
            String value = pps.getProperty(key);
            System.out.println(key + " = " + value);
            return value;

        }catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    //读取Properties的全部信息
    public static void GetAllProperties(String filePath) throws IOException {
        Properties pps = new Properties();
        InputStream in = new BufferedInputStream(new FileInputStream(filePath));
        pps.load(in);
        Enumeration en = pps.propertyNames(); //得到配置文件的名字

        while(en.hasMoreElements()) {
            String strKey = (String) en.nextElement();
            String strValue = pps.getProperty(strKey);
            System.out.println(strKey + "=" + strValue);
        }

    }

    //写入Properties信息
    public static void WriteProperties (String filePath, String pKey, String pValue) throws IOException {
        Properties pps = new Properties();

        InputStream in = new FileInputStream(filePath);
        //从输入流中读取属性列表(键和元素对)
        pps.load(in);
        //调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。
        //强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。
        OutputStream out = new FileOutputStream(filePath);
        pps.setProperty(pKey, pValue);
        //以适合使用 load 方法加载到 Properties 表中的格式,
        //将此 Properties 表中的属性列表(键和元素对)写入输出流
        pps.store(out, "Update " + pKey + " name");
    }

    public static void main(String [] args) throws IOException{
        //String value = GetValueByKey("Test.properties", "name");
        //System.out.println(value);
        //GetAllProperties("Test.properties");
        WriteProperties("Test.properties","long", "212");
    }
}

执行结果:

Test.properties中文件的数据为:

name=JJ
Weight=4444
long=212
Height=3333

(4)Collections工具类

添加

 Queue queue = new linkedList<>();
 //添加
 Collections.addAll(queue,"1","2");

二分查找

 List queue = new linkedList<>();
Collections.addAll(queue,"1","2");
Collections.sort(queue);//排序
 System.out.println(Collections.binarySearch(queue,"2")); //1

Collection与Collections区别
Collection是集合接口,Collections是集合操作工具类,二者没有本质联系;

7、关系
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/755732.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号