• Java集合框架之四大接口、常用实现类


    Java集合框架

    <Java集合框架的四大接口>

    Collection:存储无序的、不唯一的数据;其下有List和Set两大接口。

    List:存储有序的、不唯一的数据;

    Set:存储无序的、唯一的数据;

    Map:以键值对的形式存储数据,以键取值。键不能重复,但值可以重复。

    接口的常用实现类:ArrayList、LinkedList、Vector、HashSet、LinkedHashSet、TreeSet、HashMap、LinkedHashMap、TreeMap、HashTable

    一、List接口

    是一个有序集合,继承自Collection接口。现已知常用实现类有:ArrayList、LinkedList、Vector。

    1. 常用方法:

    add():在列表的最后添加元素;

    add(index,obj):在列表的指定位置添加元素;

    size():返回当前列表的元素个数

    get(int index):返回下标为index的元素;

    clear():清除列表中所有元素;

    isEmpty():检测列表是否为空;返回true/false;

    contains():传入一个对象,检测列表中是否含有该对象;

    indexOf():传入一个对象,返回该对象在列表中首次出现的地址;

    lastInsevOf():传入一个对象,返回该对象在列表中最后一次出现的地址;

    remove():传入一个下标,或者一个对象,删除指定元素;如果删除指定对象,需要重写equals()方法,比对传入的对象是不是属于原列表,如果属于,结果返回true;

    set(index,obj):用新传入的对象,将指定位置的元素替换掉,返回被替换前的元素对象;

    subList():截取一个子列表返回List类型;

    toArray():将列表转为数组,返回一个Object[]类型;

    iterator():使用迭代器遍历。

    2. 如何输出List列表?

    a. for循环;

    b. foreach遍历(比较常用);

    c. 使用迭代器遍历列表;

    3. List接口的常用实现类:

    ArrayList和LinkedList实现类是继承自List接口的,所以List的常用方法它们也是适用的。

    a. ArrayList

    ArrayList实现了一个长度可变的数组,在内存空间中开辟一串连续的空间。

    b. LinkedList

    LinkedList使用链表结构存储数据,在插入和删除元素是速度非常快。

     1 //ArrayList实现类
     2 ArrayList<String> list1=new ArrayList<String>();
     3 list1.add("第一条数据");  
     4 list1.add("第二条数据");
     5 list1.add("第三条数据");
     6 list1.add("第四条数据");
     7 list1.add("第五条数据");
     8 list1.add("第三条数据");
     9 list1.add(2,"第六条数据");  //在第三条数据后添加“第六条数据”
    10 
    11 System.out.println(list1.size()); //返回列表长度
    12 System.out.println(list1.get(2));  //返回“第六条数据”
    13 //list1.clear(); //清除所有数据
    14 System.out.println(list1.isEmpty()); //返回false
    15 System.out.println(list1.contains("第一条数据"));  //返回true
    16 System.out.println(list1.indexOf("第三条数据"));  //返回3
    17 System.out.println(list1.lastIndexOf("第三条数据"));   //返回6
    18 System.out.println(list1.remove(1));  //删除“第二条数据”
    19 System.out.println(list1.set(0, "替换第一条数据"));  //替换第一条数据
    20 List list=list1.subList(2, 5);  //截取第三到第五条数据,返回List
    21 System.out.println(list1.toString());  //转成数组
    22         
    23 //LinkedList实现类
    24 LinkedList<News> list2=new LinkedList<News>();
    25 list2.add(new News(1,"xxxxxxx","赵"));
    26 list2.add(new News(2,"sssssss","钱"));
    27 list2.add(new News(3,"yyyyyyy","孙"));
    28 list2.add(new News(4,"nnnnnnn","李"));
    29 list2.add(new News(5,"rrrrrrr","周"));
    30 System.out.println(list2.contains(new News(3,"yyyyyyy","孙")));  //返回为true;重写equals()方法;如果不重写equals()方法,返回为false;
    31 System.out.println(list2.remove(new News(1,"xxxxxxx","赵")));  //返回为true
    32         
    33                 /*
    34          * 使用for循环遍历
    35          */
    36         for (int i = 0; i < list1.size(); i++) {
    37             if(list1.get(i) instanceof String){  //判断传入的数据属不属于String类型
    38                 String str=list1.get(i);
    39                 System.out.println(str);
    40             }
    41         }
    42         /*
    43          * foreach遍历
    44          */
    45         for (News news : list2) {
    46             System.out.println(news.getId()+"   "+news.getTitle()+"	"+news.getAuthor());
    47         }
    48         /*
    49          * 迭代器遍历
    50          */
    51         Iterator<String> iter=list.iterator();
    52         while(iter.hasNext()){ //判断list有没有下一条
    53             String s=iter.next();  //字符串取到下一条
    54             System.out.println(s);
    55         }        
    56                     
     1 /**
     2  *News类
     3  */
     4 class News{
     5     private int id;
     6     private String title;
     7     private String author;
     8 
     9     @Override
    10     public boolean equals(Object obj) {
    11         if (this == obj)
    12             return true;
    13         if (obj == null)
    14             return false;
    15         if (getClass() != obj.getClass())
    16             return false;
    17         News other = (News) obj;
    18         if (author == null) {
    19             if (other.author != null)
    20                 return false;
    21         } else if (!author.equals(other.author))
    22             return false;
    23         if (id != other.id)
    24             return false;
    25         if (title == null) {
    26             if (other.title != null)
    27                 return false;
    28         } else if (!title.equals(other.title))
    29             return false;
    30         return true;
    31     }
    32     public News() {
    33         super();
    34     }
    35     public News(int id, String title, String author) {
    36         super();
    37         this.id = id;
    38         this.title = title;
    39         this.author = author;
    40     }
    41     public int getId() {
    42         return id;
    43     }
    44     public void setId(int id) {
    45         this.id = id;
    46     }
    47     public String getTitle() {
    48         return title;
    49     }
    50     public void setTitle(String title) {
    51         this.title = title;
    52     }
    53     public String getAuthor() {
    54         return author;
    55     }
    56     public void setAuthor(String author) {
    57         this.author = author;
    58     }
    59     
    60     
    61 }

    二、Set接口

    1. 常用方法:

    与List接口基本相同。但是Set接口中的元素是无序的,因此没有与下标有关的方法。例如:get(index)、remove(index)、add(index,obj)

    2. Set接口的现已知常用实现类有:

    HashSet、LinkedHashSet、TreeSet

    3. HashSet

    底层是HashMap的相关方法,传入数据后,根据数据的hashCode进行散列运算,得到一个散列值后再进行运算,确定元素在序列中存储的位置。

    所以,使用HashSet存数据必须在实体类中重写hashCode和equals方法!!

     1     //HashSet无序的
     2     Set<String> set1=new HashSet<String>();
     3     set1.add("set1");
     4     set1.add("set2");
     5     set1.add("set3");
     6     set1.add("set4");
     7     set1.add("set5");
     8 
     9     //foreach遍历
    10     for (String set : set1) {
    11         System.out.println(set);
    12     }
    13       

    4. LinkedHashSet

    在HashSet的基础上,新增了一个链表。用链表来记录HashSet种元素放入的顺序;HashSet依然是无序的,但链表会按照存入的顺序存储。

     1     //LinkedHashSet按照放入的顺序输出
     2     Set<Person> set2=new LinkedHashSet<Person>();
     3 //  set2.addAll(set1);  //追加set1的所有数据
     4     set2.add(new Person(1,"红"));
     5     set2.add(new Person(2,"黄"));
     6     set2.add(new Person(3,"蓝"));
     7     set2.add(new Person(4,"绿"));
     8     set2.add(new Person(4,"绿"));    
     9 
    10     //迭代器遍历
    11     Iterator<Person> iter=set2.iterator();
    12     while(iter.hasNext()){
    13         Person p=iter.next();
    14         System.out.println(p.getId()+"	"+p.getName());
    15     }
    16 
    17 class Person{
    18     private int id;
    19     private String name;
    20     
    21     /*
    22      * 如果不重写hashCode和equals方法,存入相同数据时将无法比对
    23      *
    24      */
    25     @Override
    26     public int hashCode() {
    27         final int prime = 31;
    28         int result = 1;
    29         result = prime * result + id;
    30         result = prime * result + ((name == null) ? 0 : name.hashCode());
    31         return result;
    32     }
    33     @Override
    34     public boolean equals(Object obj) {
    35         if (this == obj)
    36             return true;
    37         if (obj == null)
    38             return false;
    39         if (getClass() != obj.getClass())
    40             return false;
    41         Person other = (Person) obj;
    42         if (id != other.id)
    43             return false;
    44         if (name == null) {
    45             if (other.name != null)
    46                 return false;
    47         } else if (!name.equals(other.name))
    48             return false;
    49         return true;
    50     }
    51     public Person() {
    52         super();
    53     }
    54     public Person(int id, String name) {
    55         super();
    56         this.id = id;
    57         this.name = name;
    58     }
    59     public int getId() {
    60         return id;
    61     }
    62     public void setId(int id) {
    63         this.id = id;
    64     }
    65     public String getName() {
    66         return name;
    67     }
    68     public void setName(String name) {
    69         this.name = name;
    70     }
    71     
    72 }

    5. TreeSet

    将存入的数据,进行排序,然后输出。

    如果传入的是一个实体对象,那么需要传入比较器:实体类实现Comparable接口,并重写CompareTo方法;

     1     //TreeSet从小到大输出。存入元素,默认升序排序;存入实体对象,需要传入比较器
     2     Set<Person> set3=new TreeSet<Person>();
     3     set3.add(new Person(11,"a"));
     4     set3.add(new Person(22,"b"));
     5     set3.add(new Person(33,"c"));
     6     set3.add(new Person(44,"d"));
     7 
     8     //迭代器遍历
     9     Iterator<Person> iter=set3.iterator();
    10     while(iter.hasNext()){
    11         Person p=iter.next();
    12         System.out.println(p.getId()+"	"+p.getName());
    13     }
    14 
    15 class Person implements Comparable{  //实现
    16     private int id;
    17     private String name;
    18     
    19     //compareTo方法判断传入的对象和已有对象
    20     @Override
    21     public int compareTo(Object o) {
    22         Person p=null;
    23         if(o instanceof Person){
    24             p=(Person)o;
    25         }else{
    26             return 0;
    27         }
    28         return this.id -p.getId();  //为正数,升序;为负数,降序;等于0,位置不变
    29     }
    30     
    31     public Person() {
    32         super();
    33     }
    34     public Person(int id, String name) {
    35         super();
    36         this.id = id;
    37         this.name = name;
    38     }
    39     public int getId() {
    40         return id;
    41     }
    42     public void setId(int id) {
    43         this.id = id;
    44     }
    45     public String getName() {
    46         return name;
    47     }
    48     public void setName(String name) {
    49         this.name = name;
    50     }
    51     
    52     
    53 }

    三、Map接口

    1. Map接口的特点:

    以键值对的形式存储数据,以键取值。键不能重复,值可以重复。

    2. Map接口的现已知常用实现类有:

    HashMap、HashTable、LinkedHashMap、TreeMap

    3. 常用方法:

    put(key,value):向Map的最后追加一个键值对;

    get(key):通过键,取到一个值;

    clear():清除Map中的所有数据;

    containsKey(key):检测是否包含指定的键;

    containsValue(obj):检测是否包含指定的值;

    replace():替换指定键的值;

    4. 遍历Map

    a. keySet():返回Set,先取键,再取值;

    b. values():返回Collection,直接取值;

    c. 取代一个entry键值对,返回Set<Entry<>>;

     1         Map<String, String> map1=new HashMap<String, String>();
     2         map1.put("01", "aaaaaa");
     3         map1.put("02", "bbbbbb");
     4         map1.put("03", "cccccc");
     5         map1.put("04", "dddddd");
     6 //        map1.clear();  //清除所有数据
     7         System.out.println(map1.containsKey("01"));  //返回true
     8         System.out.println(map1.containsValue("aaaa"));  //返回false
     9         System.out.println(map1.replace("03", "dddddd"));  //将cccccc替换为dddddd
    10         System.out.println(map1.get("02"));  //返回bbbbbb
    11         
    12         /**
    13          * 遍历Map的方式一,先取键,再取值
    14          */
    15         Set<String> keys=map1.keySet();  //取到所有键
    16         Iterator<String> iter=keys.iterator();
    17         while(iter.hasNext()){ //迭代器遍历取到每一个键
    18             String key=iter.next();
    19             System.out.println(key+"  "+map1.get(key)); //key:取到键    map1.get(key):取到每个键对应的值
    20         }
    21         
    22         /**
    23          * 遍历Map的方式二,直接取值;只能取到值
    24          */
    25         Collection<String> values = map1.values();
    26         Iterator<String> iter1= values.iterator();
    27         while(iter1.hasNext()){
    28             System.out.println(iter1.next());
    29         }
    30         
    31         /**
    32          * 遍历Map的方式三,取到一个entry键值对
    33          */
    34         Set<Entry<String,String>> set= map1.entrySet();
    35         Iterator<Entry<String,String>> iter2=set.iterator();
    36         while(iter2.hasNext()){
    37             Entry<String,String> entry=iter2.next();
    38             System.out.println(entry.getKey()+"  "+entry.getValue());
    39         }
    40         

    5. LinkedHashMap

    可以使用列表,记录数据放入的次序,输出的顺序与放入的顺序一致。与LinkEDHashSet一样。

    6. TreeMap

    根据键的顺序,进行排序后输出。与TreeSet。

    如果传入的是实体对象,必须重写比较函数。

    7. HashMap和HashTable的区别?

    a. HashTable是线程安全的,HashMap是线程不安全的;

    b. HashTable的键不能为null,HashMap的键可以为null;

    c. HashTable继承自Dirctionary字典类,HashMap继承自abstract类;

    d. 扩容大小:HashTable两倍,HashMap两倍加一;

    e. 初始容量:HashTable为11,HashMap为16;两者的填充因子默认都是0.75;

  • 相关阅读:
    Python笔记_函数,模块,包的关系
    「GXOI / GZOI2019」宝牌一大堆
    「BalticOI 2020」村庄 (贪心)
    CF Round #635 Div.1 Chiori and Doll Picking (hard version)
    「BalticOI 2020」病毒
    「BalticOI 2020」小丑
    「BalticOI 2020」混合物
    k短路
    「JSOI2019」神经网络
    「NOI2020」时代的眼泪
  • 原文地址:https://www.cnblogs.com/yanglianwei/p/8847861.html
Copyright © 2020-2023  润新知