A brief introduction and application of a set of Java Collection

1 Collections Overview

  • Set : a collection container provided in java, it can be used to store a plurality of data.
    Collection and an array of differences:
  • Length of the array is fixed. The collection length is variable.
  • Stored in the array element of the same type, you can store basic data type value. Collection of objects are stored. And the type of the object can be inconsistent. When the object is generally more time, use the collection is stored in development.

A set of frame 2

Memory structure according to which a collection may be divided into two categories, namely, a set of single java.util.Collectionand dual column set java.util.Map, where the record about the main Collectionset.

  • Collection : root interface separate collections for storing a series of elements that meet certain rules, it has two important sub-interfaces, respectively, java.util.Listand java.util.Set. Wherein Listthe characteristic element is ordered, the element can be repeated. SetThe disorder is characterized by an element, and not repeatable. ListThe main interface implementation class there java.util.ArrayListand java.util.LinkedList, Setthe main interface implementation class has java.util.HashSetand java.util.TreeSet.

As shown below:
Here Insert Picture Description
the collection itself is a tool, it is stored in the java.util package. In Collectionthe interface definition of the most common single set of frame content.

3 Collection commonly used functions

Collection of all single parent interface is set, thus defining a single common set of methods (and List Set) in Collection, these methods can be used to operate all separate collection. Methods as below:

  • public boolean add(E e): The given object to the current collection.
  • public void clear() : Empty the collection of all the elements.
  • public boolean remove(E e): Delete the given object in the current collection.
  • public boolean contains(E e): Analyzing current collection contains the given object.
  • public boolean isEmpty(): To determine whether the current collection is empty.
  • public int size(): Returns the number of elements in a set.
  • public Object[] toArray(): The set of elements stored in the array.

Method Example:

  Collection<String> list = new ArrayList<>();//集合为空
        list.add("a");//[a]
        list.add("a");//[a,a]
        list.clear();//[]
        list.add("b");//[b]
        list.add("b");//[b,b]
        list.add("c");[b,b,c]
        System.out.println(list.contains("c"));//true
        System.out.println(list.isEmpty());//false
        System.out.println(list.size());//3
        Object[] objects = list.toArray();
        for (Object object : objects) {
            System.out.println(object);//b,b,c
        }
Published 26 original articles · won praise 5 · Views 1904

Guess you like

Origin blog.csdn.net/weixin_43840862/article/details/105013645