Collection classes List, Set, Map for Java learning

The specific introduction to the implementation classes such as ArrayList has time to write an article, here is just a brief introduction

Collection class overview

Collection classes are also called containers. Similar to arrays, they can store certain data, but they are different.
Comparing arrays and sets
Commonly used collections are List, Set, and Map. The interfaces List and Set inherit the Collection interface, and each interface also provides different implementation classes.
Inheritance relationship of common collection classes
Before talking about common collections, let's mention the Collection class. The Collection class is the root interface in the hierarchy. The units that make up a Collection are called elements . All classes that implement the Collection interface must provide two standard organ functions: an organ function with no parameters is used to create an empty Collection, and an organ function with a Collection parameter is used to create a new Collection. The incoming Collection has the same elements. The latter function allows the user to copy a Collection. The methods provided by this class are described below: The
Collection method
content is excerpted from the Java API manual.
The commonly used ones are add(), remove(), isEmpty(), iterator(), and size().

When traversing the data in the collection, iterators are often used to obtain the iterator of the collection, so here is a brief introduction to the iterator:

Iterator

Iterator is an interface for traversing elements in a collection. All collection classes implement the Iterator interface.
Here are the methods of the iterator class from the Java API manual:
iterator
As an example:

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Demo {
    public static void main(String[] args) {
        Collection<String> list=new ArrayList<String>();    //初始化元素类型为String的容器
        list.add("a");          //向集合中添加元素
        list.add("b");
        list.add("c");
        Iterator<String> it=list.iterator();    //返回迭代器的值
        while(it.hasNext()){                    //判断存在 下一个数值
            String str=(String)it.next();       //返回迭代器的下一个元素
            System.out.println(str);
        }
    }
}

The output is:

a
b
c

It needs to be reminded here that the next() method of Iterator returns an Object, so it needs to be cast to the String class.

List collection

The List collection inherits the Collection class. The elements in the collection are allowed to be repeated . The order of each element is the insertion order of the objects. Except for iterators, List is similar to an array . ) to access elements in the collection.

The List interface inherits the Collection and defines new methods:
the following are the methods of the List interface in the API manual:
list1
list2
the most commonly used are the following two:
get(int index); Get the element at the specified index position, and realize the The function of index lookup.
set(int index,Object obj); Modify the element at the specified position of the index to the specified object.
The implementation class of the List interface:
1. ArrayList class (dynamic array): allows to save all elements (including null), non-thread-safe, orderly inserted data, fast element search, but because inserting data involves memory operations such as element movement, Therefore, the addition and deletion operations are slower. The ArrayList class uses an array format to store data, and the number of array elements is larger than the actual stored data in order to grow and insert elements.
2. LinkedList class: The linked list structure is used to save objects, which is convenient for adding and deleting objects, and it is slow to find objects.
Code example:

import java.util.ArrayList;
import java.util.List;

public class Gather {
    public static void main(String[] args) {
        List<String> list=new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("c");
        int m=(int)(Math.random()*list.size());
        System.out.println("随机数对应的元素值为:"+list.get(m));
        list.remove(2);             //索引值是从0开始的,即2对应的索引值为“c”
        list.remove("b");
        System.out.println("删除索引是‘2’的元素后和值为“c”的元素之后,数组遍历结果为:");
        for(int i=0;i<list.size();i++){
            System.out.println(list.get(i));
        }
    }
}

The output is:

随机数对应的元素值为:c
删除索引是‘2’的元素后和值为“c”的元素之后,数组遍历结果为:
a

Set collection

Compared with the List collection, the objects in the Set collection are not sorted in a specific way, but simply add objects to the collection, but the Set collection cannot contain duplicate objects . Similarly, the Set inherits from the Collection class.
Set common implementation classes:

  1. The HashSet class is backed
    by a hash table (HashMap instance). The iteration order of the Set is not guaranteed, in particular it does not guarantee that the order will be constant, and null elements are allowed.
  2. The TreeSet class
    not only implements the Set interface, but also implements the java.util.SortedSet interface. Therefore, the TreeSet class implements the Set collection and sorts it according to the natural order when traversing the collection. It can also use the comparator to compare the objects in the Set collection implemented by the TreeSet class. put in order.
    (There is also an AbstractMap class that is used less, if you touch it later, it will be added)
    method
    method
    method
    method

For TreeSet traversing the collection in ascending order according to the natural order, but does not allow elements to be repeated, refer to the
Comparable interface:

This interface enforces an overall ordering of objects of each class that implements it. This ordering is called the class's natural ordering, and the class's compareTo method is called its natural comparison method. The compareTo() method is used to compare the order of this object with the specified object.

Here is a code example of TreeSet:

import java.util.Iterator;
import java.util.TreeSet;

public class UpdateStu implements Comparable<Object> {
    String name;
    long id;
    public UpdateStu(String name,long id){
        this.id=id;
        this.name=name;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }

    @Override
    public int compareTo(Object o) {
        // TODO Auto-generated method stub
        UpdateStu upstu=(UpdateStu)o;
        int result=id>upstu.id?1:(id==upstu.id?0:-1);   //比较当前类和传入的类的id大小,如果根据比值的情况,分别返回1,0,-1
        return result;
    }
    public static void main(String[] args) {
        UpdateStu stu1=new UpdateStu("李同学",00101);
        UpdateStu stu2=new UpdateStu("张同学",00102);
        UpdateStu stu3=new UpdateStu("刘同学",00103);
        UpdateStu stu4=new UpdateStu("王同学",00104);
        TreeSet<UpdateStu> tset=new TreeSet<UpdateStu>();
        tset.add(stu3);
        tset.add(stu2);
        tset.add(stu1);
        tset.add(stu4);
        Iterator<UpdateStu> iter=tset.iterator();
        System.out.println("遍历tset集合中的元素");
        while(iter.hasNext()){
            UpdateStu stu=(UpdateStu)iter.next();       //next()方法返回的是Object,所以要对其进行类型转换
            System.out.println(stu.getI  d()+" "+stu.getName());
        }
        iter=tset.headSet(stu3).iterator();
        System.out.println("截取stu3前面的部分集合");
        while(iter.hasNext()){
            UpdateStu stu=(UpdateStu)iter.next();       
            System.out.println(stu.getId()+" "+stu.getName());
        }
        iter=tset.subSet(stu1, stu3).iterator();
        System.out.println("截取stu1和stu3中间部分的集合");
        while(iter.hasNext()){
            UpdateStu stu=(UpdateStu)iter.next();       
            System.out.println(stu.getId()+" "+stu.getName());
        }
        iter=tset.tailSet(stu2).iterator();
        System.out.println("截取stu2之后的集合");
        while(iter.hasNext()){
            UpdateStu stu=(UpdateStu)iter.next();       //定义一个局部的UpdateStu变量,便于下行的数据输出
            System.out.println(stu.getId()+" "+stu.getName());
        }

    }

}

Code description: The Set collection stored in the TreeSet class must implement the Comparable interface. The compareTo(Object o) method in the interface compares the order of this object and the specified object.

Map collection

The Map collection does not inherit the Collection interface. It provides a key-to-value mapping. A value can be mapped by multiple keys, but a key can only point to one value, and the key values ​​cannot be the same.
The following are common methods of Map:

method name effect
put(K key,V value) Add the specified key and value mapping relationship to the collection
containsKey(Object key) Returns true if this map contains the mapping for the specified key
containsValue(Object value) Returns true if this map maps one or more keys to the specified value
get(Object key) If the specified key exists, return the value corresponding to the object, otherwise return null
keySet() Returns the Set collection formed by all key objects in the collection
values() Returns a Collection of all value objects in this object

Code example:

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class UpStu {
    public static void main(String[] args) {
        Map<String,String> map=new HashMap<String,String>();
        map.put("01","李同学");
        map.put("02", "张同学");
        map.put("03", "王同学");
        System.out.println("查找是否有编号为02的同学:"+map.containsKey("02"));
        System.out.println("查找是否有王同学:"+map.containsValue("王同学"));
        Set<String> set=map.keySet();   //获取key的集合
        Collection<String> coll=map.values();   //获取values的集合
        Iterator<String> siter=set.iterator();
        Iterator<String> citer=coll.iterator();
        System.out.println("key集合中的元素:");
        while(siter.hasNext()){
            String str=(String) siter.next();
            System.out.println(str);
        }
        System.out.println("values集合中的元素:");
        while(citer.hasNext()){
            String str=(String)citer.next();
            System.out.println(str);
        }
    }
}

result:

查找是否有编号为02的同学:true
查找是否有王同学:true
key集合中的元素:
01
02
03
values集合中的元素:
李同学
张同学
王同学

Objects in the Map collection are allowed to be null, and there is no limit on the number of them.
The implementation class of the Map interface

HaspMap : It is recommended to use the HashMap collection to implement the Map collection, because the Map collection implemented by this class is more efficient to add and delete mapping relationships. This class is an implementation of the Map interface based on a hash table. It can quickly find its internal mapping relationship through a hash code. Null values ​​and null keys are allowed, but the uniqueness must be guaranteed.
TreeMap : The Map collection implemented by the TreeMap class has a certain order. When an ordered Map collection is required, TreeMap can be considered, and the key value is not allowed to be null.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

class Emp{
    private String name;
    private String id;
    public Emp(String id,String name){
        this.id=id;
        this.name=name;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }

}
public class MapText {
    public static void main(String[] args) {
        Map<String,String> map=new HashMap<String,String>();
        Emp emp1=new Emp("001","张三");
        Emp emp2=new Emp("002","李四");
        Emp emp3=new Emp("003","王一");
        Emp emp4=new Emp("004","赵六");
        Emp emp5=new Emp("005","黄七");
        Emp emp6=new Emp("006","牛二");

        map.put(emp2.getId(), emp2.getName());
        map.put(emp4.getId(), emp4.getName());
        map.put(emp1.getId(), emp1.getName());
        map.put(emp3.getId(), emp3.getName());
        map.put(emp6.getId(), emp6.getName());
        map.put(emp5.getId(), emp5.getName());

        Set<String> set=map.keySet();
        Iterator<String> siter=set.iterator();
        System.out.println("HashMap类实现的Map集合,无序");
        while(siter.hasNext()){
            String key=(String)siter.next();        //获取下个迭代器的值,即key
            String name=(String)map.get(key);       //调用map.get()方法,根据映射,返回key对象对应的值
            System.out.println(key+" "+name);       
        }
        System.out.println("Treemap类实现的Map集合,有序");
        TreeMap<String,String> treemap=new TreeMap<String,String>();
        treemap.putAll(map);            //将map对象中的所有值赋给treemap
        Iterator<String> titer=treemap.keySet().iterator();     
        while(titer.hasNext()){
            String key=(String)titer.next();        //获取下个迭代器的值,即key
            String name=(String)map.get(key);       //调用map.get()方法,根据映射,返回key对象对应的值
            System.out.println(key+" "+name);
        }
    }
}

result:

查找是否有编号为02的同学:true
查找是否有王同学:true
key集合中的元素:
01
02
03
values集合中的元素:
李同学
张同学
王同学

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326004442&siteId=291194637