Home > Java > javaTutorial > Detailed explanation of java collection framework

Detailed explanation of java collection framework

高洛峰
Release: 2017-01-23 10:29:17
Original
1806 people have browsed it

1. Overview of java collection framework

java SE includes the java Collection Framework (java Collection Framework, referred to as JCF), which is composed of a set of classes and interfaces. Its main function is to store stored data in The goal is to provide a common framework for processing object collections and reduce the amount of coding required by programmers when processing different object collections.

Some differences among collection classes, in addition to whether they support repeated element operations, include whether elements are ordered and whether null elements are allowed to be added. Based on these three differences, the java collection framework divides the storage methods of objects into three types, which are:

Set (set): The objects in the object container have no order and cannot be repeated.

List (list): The objects in the object container are sorted according to index order, and there can be duplicate objects.

Map (mapping): The elements in the object container contain a pair of "key object-value object" mapping, where the key object cannot be repeated and the value object can be repeated.

In order to support object sorting and traversal access operations, the Java collection framework provides several interfaces:

The interface SortedSet provides filming functions for Set type containers.

Interface SortedMap provides sorting of key objects for Map type containers.

Interfaces Comparable and comparator are used to sort objects in the collection.

2.Collection interface and Iterator interface

The Collection interface defines some basic methods common to Collection objects

Detailed explanation of java collection framework

The Iterator interface is a An interface for traversing collections.

Detailed explanation of java collection framework

1.List interface

The List interface inherits from the Collection interface. It has the following characteristics:

The elements in the List are in order of.

List usually allows duplicate elements.

List implementation classes usually support null elements.

Elements in the List object container can be accessed through indexes.​

The most commonly used implementation classes of 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(&#39;a&#39;);
      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));
      }
    }
  }
Copy after login

The equals() method defined by the Object class can only be used when the object passed to the method is the same as the object calling the method. Object will return true. You can treat two objects with the same state as the same object by overriding the equals() method.

2).LinkedList

Detailed explanation of java collection framework

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));  
      }  
    }
  }
Copy after login

Selection of LinkedList and ArrayList

If the list needs to be fast Access, but do not frequently insert and delete elements, then it would be better to choose ArrayList; if you need to perform frequent insertion and deletion operations on the list, then you should choose LinkedList.

2.set interface

The set interface inherits from the Collection interface and also inherits all methods of the Collection interface. The set interface has the following characteristics:

Set type containers cannot contain duplicate elements. When adding an element to the container, it is necessary to compare whether the content of the element is duplicated, so the object added to the Set type object container must override the equals() method.

Elements may or may not be in order.

Because the elements may not be in order, the elements in the Set cannot be accessed based on subscripts.

The HashSet class and TreeSet class are most commonly used to implement the Set interface.

1).Hashset

The Hashset class is a Set interface implementation based on the hash algorithm. It mainly has the following characteristics:

When traversing the Hashset, the elements in it There is no order.

Duplicate elements are not allowed in Hashset. The duplicate elements here refer to two objects that have the same hash code and return true when compared using the equals() method.

Allows to contain null elements.

If the class we write redefines the equals method, then this class must also redefine the hashCode() method, and ensure that when the comparison result of two objects using the equals method is true, the hashCode of the two objects () method return values ​​are equal.

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);
      }
    }
  }
Copy after login

2).TreeSet

The TreeSet class not only implements the Set interface, but also implements the SortedSet interface, thereby ensuring that the objects in the collection are in a certain order Sort. When an object is added to the TreeSet collection, it will be inserted into the ordered sequence of objects. However, this sorting is not sorted according to the order in which the objects are added, but according to a certain algorithm.

TreeSet sorts the elements using their natural order, or according to the Comparator provided when creating the Set. TreeSet supports two sorting methods: natural sorting and custom sorting.

3.Map interface

Map(映射)接口是java集合框架中不同于Collection接口的另一个重要接口,它对应的是在一种从键(Key)到值(Value)的对应关系的集合。Map类型的对象容器里面保存着两组对象,一组对象用于保存Map里的Key,另外一组用于保存Value。Key和Value可以升级任何引用类型的数据。Key不能重复,但是Value可以重复。

1).HashMap

HashMap是基于哈希算法的Map接口的实现。HashMap将它的键保存在哈希表中进行维护,键是唯一的。但是,HashMap并不保证键以特定顺序排列,特别是不保证顺序永久不变。

HashMap类实现了Map接口,从而具有Map接口的所有方法。

package day1228;
  import java.util.*;
  public class HashMapDemo {
    public static void main(String[] args) {
      // 创建一个新的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");
      // 使用iterator遍历 键和值
      System.out.println("之前的Map值是:");
      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);
      }
      // 删除键为"a4"的值
      System.out.println("\n删除键值为a4的元素");
      map.remove("a4");
      // //使用iterator遍历 键和值
      System.out.println("\n之后的Map值:");
      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);
      }
    }
  }
Copy after login

2).TreeMap

TreeMap类是基于红黑树算法的Map接口实现。TreeMap中键的存放方式与TreeSet相似,它将键存放在树中,键的顺序按照自然顺序或者自定义顺序两种方式排列。

程序实例:

package day1228;
  import java.util.*;
  public class TreeMapDemo {
    public static void main(String[] args) {
      //创建一个新的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");
      //使用iterator显示键和值
      System.out.println("之前的map值为:");
      Set<Integer> keys=map.keySet();
      for(Object key:keys){
        String value=map.get(key);
        System.out.println(key+"="+value);
      }
      //删除键为3的值
      System.out.println("\n删除键值为3的元素");
      map.remove(3);
      //使用iterator显示键和值
      System.out.println("\n之后的值Map为:");
      for(Object key:keys){
        String value=map.get(key);
        System.out.println(key+"="+value);
      }
    }
  }
Copy after login

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持PHP中文网!

更多Detailed explanation of java collection framework相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template