java collection framework details

  • 2020-05-27 05:43:30
  • OfStack

1. Overview of the java collection framework

java SE contains composed of 1 set of classes and interfaces java collections framework (java Collection Framework, JCF), its main function is used to store data in a certain organization structure, and to access the data in a particular way, the goal is to provide a universal framework for dealing with a collection of objects, cutting down on the amount of code programmers when handling different collection of objects.

One of the differences in the collection class is that, in addition to whether they support repeating element operations, they also include whether the elements are in order and whether null elements are allowed to be added. According to these three differences, the storage mode of objects in java collection framework is divided into three types, which are:

Set (set) : objects in an object container have no order and cannot be repeated. List(list) : the objects in the object container are sorted by index and can have duplicate objects. Map (mapping) : the element in the object container contains a pair of key-object-value object mappings, where the key object cannot be repeated and the value object can be repeated.

To support object sorting and traversal access, the java collection framework provides several interfaces:

Interface SortedSet provides filming for Set type containers. Interface SortedMap provides sorting of key objects for Map type containers. The interfaces Comparable and comparator are used to sort objects in collections.

2.Collection interface and Iterator interface

The Collection interface defines some basic methods common to Collection objects

方法  描述
int size() 返回当前集合中包含的元素个数 
isEmpyt() 判断集合中是否含有元素
boolean contains(Objact o) 判断集合中是否含有某1指定元素
add(Objact o) 向集合中添加某1个元素
remove(Objact o) 从集合中删除某1元素
Iterator iterator() 返回1个遍历器,用来访问集合中的各个元素

The Iterator interface is an interface for traversing a collection.

Iterator接口中的方法
方法 描述
hasNext() 如果集合中还有更多元素,该方法返回true
next() 返回集合中的下1个元素
remove() 删除Iterator返回的最后1个元素

1. List interface

The List interface inherits from the Collection interface and has the following features:

The elements in List are ordered. List generally allows repeating elements. The implementation class of List usually supports the null element. The elements in the List object container can be accessed by index.

The most commonly used implementation classes for the List interface are the ArrayList class and the LinkedList class.

1). ArrayList

Program example:


package lei;
  import java.util.ArrayList;
  import java.util.List;
  public class Test {
    public static void main(String[] args) {     
      List list = new ArrayList<>();
      list.add(1);
      list.add("zhangsan");
      list.add(false);
      list.add('a');
      list.add(0, "lisi");
      list.add(1);
      list.remove(1);
      list.remove(2);
      list.set(0, "wangwu");
      for (int i = 0; i < list.size(); i++) {
        System.out.println(list.get(i));
      }
    }
  }

The equals () method defined by the Object class returns true only if the object passed to the method is the same object as the object that called the method. You can override the equals () method to treat two objects that have the same state as one object.

2). LinkedList

方法 描述
void addFirst 在链表开头添加1个对象
void addLast 在链表末尾添加1个对象
getFirst() 返回链表中的第1个元素
getLast() 返回链表中的最后1个元素
removeFirst() 删除链表中的第1个元素
removeLast() 删除链表中的最后1个元素

Program example:


package lei;
  import java.util.LinkedList;
  import java.util.List;
  public class Test2 {
      public static void main(String[] args) {
       LinkedList l=new LinkedList<>();
      l.add("zhangsan");
      l.add("lisi");
      l.addFirst(1);
      l.addLast(4);
      System.out.println(l.getFirst());
      System.out.println(l.getLast());
      l.removeFirst();
      l.removeLast();
      for (int i = 0; i < l.size(); i++) {
        System.out.println(l.get(i));  
      }  
    }
  }

LinkedList and ArrayList options

If the list needs quick access but does not often insert or delete elements, ArrayList is better. If need be right; The list is frequently inserted and deleted, so LinkedList should be selected.

2. set interface

The set interface inherits from the Collectiion interface, as well as all the methods of the Collection interface. set interface has the following features:

A container of type Set cannot contain duplicate elements. When an element is added to a container, the contents of the element are compared for duplicates, so an object that adds an Set type object container must override the equals() method. Elements can or may not have order. Because elements may not be in order, access to Set intermediate elements cannot be based on subscripts.

The most common implementations of the Set interface are the HashSet class and the TreeSet class.

1). Hashset

Hashset class is the implementation of Set interface based on hash algorithm. It mainly has the following features:

When traversing Hashset, the elements are in no order. Duplicate elements are not allowed in Hashset. The repeating element here means that two objects of true are returned when they have the same hash code and are compared using the equals() method. null elements are allowed.

If we write a class that redefines the equals method, then the class must also redefine the hashCode() method and ensure that when two objects are compared with the equals method to true, the return values of the hashCode() method of the two objects are the same.

Program example:


package lei;
  import java.util.HashSet;
  import java.util.Set;
  public class Test4 {
      public static void main(String[] args) {
      Set<String> set=new HashSet<String>();
      set.add("zhangsan");
      set.add("lisi");
      for(String s:set){
        System.out.println(s);
      }
    }
  }

2). TreeSet

The TreeSet class implements not only the Set interface, but also the SortedSet interface, thus ensuring that the objects in the collection are sorted in a 1-specified order. When an object is added to the TreeSet collection, it is inserted into an ordered sequence of objects, but this sort is not sorted by the order in which the objects are added, but by a definite algorithm.

TreeSet sorts elements using their natural order, or according to Comparator provided when Set was created. TreeSet supports both natural sorting and custom sorting.

3. Map interface

The Map(mapping) interface is another important interface in the java collection framework that is different from the Collection interface, which corresponds to a set of corresponding relationships from the key (Key) to the value (Value). The Map object container holds two groups of objects, one for Key in Map and one for Value. Key and Value can upgrade data of any reference type. Key cannot be repeated, but Value can be repeated.

1).HashMap

HashMap is the implementation of Map interface based on hash algorithm. HashMap keeps its keys in a hash table for maintenance, and the keys are one-only. However, HashMap does not guarantee that the keys are arranged in a particular order, especially if the order is permanent.

The HashMap class implements the Map interface and thus has all the methods of the Map interface.


package day1228;
  import java.util.*;
  public class HashMapDemo {
    public static void main(String[] args) {
      //  create 1 A new one HashMap
      Map<String, String> map = new HashMap<String, String>();
      map.put("a1", "xiao");
      map.put("b2", "xiaol");
      map.put("a4", "xiaosd");
      map.put("b1", "12a");
      map.put("a3", "1");
      //  use iterator traverse   Keys and values 
      System.out.println(" Before the Map Values are: ");
      Set<String> keys = map.keySet();
      for (Iterator<String> i = keys.iterator(); i.hasNext();) {
        String key = i.next();
        String value = map.get(key);
        System.out.println(key + "=" + value);
      }
      //  The delete key is "a4" The value of the 
      System.out.println("\n The delete key value is a4 The elements of the ");
      map.remove("a4");
      // // use iterator traverse   Keys and values 
      System.out.println("\n After the Map Value: ");
      keys = map.keySet();
      for (Iterator<String> i = keys.iterator(); i.hasNext();) {
        String key = i.next();
        String value = map.get(key);
        System.out.println(key + "=" + value);
      }
    }
  }

2).TreeMap

The TreeMap class is an Map interface implementation based on the red-black tree algorithm. The keys in TreeMap are stored in a tree similar to TreeSet, in either natural or custom order.

Program example:


package day1228;
  import java.util.*;
  public class TreeMapDemo {
    public static void main(String[] args) {
      // create 1 A new one TreeMap
      Map<Integer, String> map = new TreeMap<Integer, String>();
      map.put(1, "one");
      map.put(2, "two");
      map.put(3, "three");
      map.put(4, "four");
      map.put(5, "five");
      // use iterator Displays keys and values 
      System.out.println(" Before the map Value is: ");
      Set<Integer> keys=map.keySet();
      for(Object key:keys){
        String value=map.get(key);
        System.out.println(key+"="+value);
      }
      // The delete key is 3 The value of the 
      System.out.println("\n The delete key value is 3 The elements of the ");
      map.remove(3);
      // use iterator Displays keys and values 
      System.out.println("\n After the value of the Map To: ");
      for(Object key:keys){
        String value=map.get(key);
        System.out.println(key+"="+value);
      }
    }
  }

Related articles: