Collection of Java Basics

List collection

List of elements in the set of ordered, repeatable set each element has its corresponding index order.

List Analyzing two equal objects, simply by comparing the equals method to return true.

Look at an example:

public class A {
    public boolean equals(Object obj) {
        return true;
    }
}

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

public class ListTest2 {
    public static void main(String[] args) {
        List books = new ArrayList();
        books.add(new String("a"));
        books.add(new String("b"));
        books.add(new String("c"));
        System.out.println(books);
        books.remove(new A());
        System.out.println(books);
        books.remove(new A());
        System.out.println(books);
    }
}

When you try to delete an object is A, List A will call object equals method in order to compare the set of elements. Returns true if the equals method to a set of elements as a parameter, List will delete the element. Here A rewrite of the equals method always returns true, so every time remove an element from a List collection.

ArrayList class

ArrayList class is a class array based List implementation, fully supports all of the features described earlier List interface.

ArrayList package a dynamic, allowing redistribution Object [] array.

Set collection

HashSet class

  • No sequence element, the element may be a value set null

  • When not synchronized HashSet, assuming a plurality of threads simultaneously modified HashSet collection, which must ensure the synchronization codes by

HashSet equal elements determined criteria by comparing two objects are equal equals (), while the two objects hashCode () returns the values ​​are equal.

hashCode and equals in line with such a convention: return true equals, hashCode must be equal. Many libraries in Java code in this convention are using these two methods, such as HashSet. This is why we ask if a class overrides hashCode method, you must override equals methods, and to ensure implementation of the agreement in line with

When the HashSet into a collection element, HashSet calls hashCode () method to obtain the target value of the object hashCode, and then determining the position of the object is stored in accordance with the HashSet hashCode value.

Each slot can store HashSet element called bucket (bucket). If the value of the plurality of elements of the same hashCode, they are returned by the comparison method equals false, it is necessary to put a plurality of elements in a bucket, which can cause performance degradation. When it is, you are recommended to save objects to the HashSet collection of a class, the class rewrite equals and hashCode methods, try to ensure that returns true equals method by comparing two objects, their hashCode method returns a value equal.

When adding objects to the HashSet variable, you need to be especially careful, try not to modify the variable object involved in the calculation hashCode (), instance variables equals () method, otherwise it will lead to HashSet can not access these collections elements correctly.

Look at an example:

public class R {
    int count;
    public R(int count) {
        this.count = count;
    }
    public String toString() {
        return "R[count:" + count + "]";
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj != null && obj.getClass() == R.class) {
            R r = (R)obj;
            return this.count == r.count;
        }
        return false;
    }
    public int hashCode() {
        return this.count;
    }
}

import java.util.HashSet;
import java.util.Iterator;

public class HashSetTest2 {
    public static void main(String[] args) {
        HashSet hs = new HashSet();
        hs.add(new R(5));
        hs.add(new R(-3));
        hs.add(new R(9));
        hs.add(new R(-2));
        System.out.println(hs);
        Iterator it = hs.iterator();
        R first = (R)it.next();
        first.count = -3;
        System.out.println(hs);
        hs.remove(new R(-3));
        System.out.println(hs);
        System.out.println("hs 是否包含 count 为 -3 的 R 对象" + hs.contains(new R(-3)));
        System.out.println("hs 是否包含 count 为 -2 的 R 对象" + hs.contains(new R(-2)));
    }
}

/*
[R[count:-2], R[count:-3], R[count:5], R[count:9]]
[R[count:-3], R[count:-3], R[count:5], R[count:9]]
[R[count:-3], R[count:5], R[count:9]]
hs 是否包含 count 为 -3 的 R 对象false
hs 是否包含 count 为 -2 的 R 对象false
*/

LinkedHashSet class

LinkedHashSet HashSet subclass is likewise determined based on the storage position of the element hashCode value. But the use of the list of elements to maintain order so that when LinkedHashSet traverse the collection of elements, LinkedHashSet will visit the collection by adding the elements of the order of elements.

LinkedHashSet need to maintain insertion order, performance was slightly lower than HashSet, but will have a good performance when accessing Set in the iteration all the elements, because it lists to maintain internal order.

TreeSet class

TreeSet SortedSet interface implementation class is, as the name suggests this is a sort of Set collection.

TreeSet underlying the TreeMap implementation, red-black tree data structure used to store a collection of elements. TreeSet supports two sorting methods: natural sorting and custom ordering. By default, using natural ordering.

Natural order

Java provides Comparable interface, interface defines a compareTo (Object obj) method. Class that implements the interface must implement the abstract methods.

compareTo (Object obj) comparison rules are as follows:

  • obj1.compareTo (obj2) returns a value of 0, indicating equal
  • obj1.compareTo (obj2) returns a value greater than 0, indicating obj1> obj2
  • obj1.compareTo (obj2) returns a value less than 0, indicating obj1 <obj2

TreeSet will call the set of elements compareTo (Object obj) method to compare the relationship between the size of the element, then the set of elements in ascending order, this is the natural order. So naturally the sort of element object must implement the Comparable interface.

If two objects are equal by comparing compareTo (Object obj), i.e., the return value is 0, TreeSet that they are equal, then the new object will not be added to the collection TreeSet.

If you want TreeSet to work properly, TreeSet can only add objects of the same type.

Custom sorting

If you want a custom sort, you need to when you create a TreeSet collection of objects, a collection of objects associated with the Comparator TreeSet. Comparator interface is a function, an expression may be used instead of Lambda.

By customizing the sort, still can not add different types of objects to the TreeSet, otherwise a ClassCastException exception. At this time, the set of elements is determined equal to two criteria: Comparator returned by comparing two elements 0, so would not TreeSet second element added to the collection.

import java.util.TreeSet;

public class TreeSettest4 {
    public static void main(String[] args) {
        TreeSet ts = new TreeSet((o1, o2) -> {
            M m1 = (M) o1;
            M m2 = (M) o2;
            return m1.age > m2.age ? -1 : m1.age < m2.age ? 1: 0;
        });
        ts.add(new M(5));
        ts.add(new M(-3));
        ts.add(new M(9));
        System.out.println(ts);
    }
}

Using the above target type for the Lambda expressions Comparator, which is responsible for sorting ts collection. All M class without implementing the Comparable interface, but the sort of elements responsible for Lambda expressions TreeSet association.

When implementing compareTo method, it is strongly recommended consistent with equals results, otherwise some strange errors may occur. The class is because some equals to determine reproducibility, the use of some sort of natural x.compareTo (y) == 0 is determined. compareTo is to determine the position of the element in the sort of equality, equals is to determine whether the same element, since a decision ordering position, a decision are equal, so we need to ensure the very same position when ordering, which equals should be equal.

EnumSet class

EnumSet is designed for enumeration class design collections, all of the elements in the EnumSet must be specified enumerated type enumeration class, the enumeration type specify an explicit or implicit in the creation of EnumSet.

EnumSet the collection elements is ordered to the sequence of enumerated values ​​in order to determine the class Enum collection element. EnumSet collection does not allow insertion of null elements.

Internal EnumSet represented as a bit vector, which is stored in the form of compact and efficient, very small memory footprint, high operating efficiency. Especially during bulk operations, such as call containsAll retainAll method and time.

Map collection

Defined: Map for storing data having a mapping relationship, a one-way one relationship exists between the key and the value, key must be unique.

The relationship between the Set and Map are very close, if the key-value pair as a key value of the client, where the key, value it where it is. This can be treated Map Set as a treat.

Indeed, Map Entry provides a class to encapsulate the internal key-value pairs, and considering only the calculation of Key Entry Entry storage package. From the point of view source code, Java is to achieve a Map, and then all of a null value are realized on the Map Set collection by packaging.

HashMap implementation class

HashMap used as key objects must implement the hashCode () method and equals () methods.

Analyzing equal HashMap two key criteria: returns true key by comparing two equals () method, hashCode two key values ​​are also equal.

HashMap two equal value determination criteria: the method returns true two objects can pass equals ().

And HashSet Similarly, when using the HashMap custom class as a key, if the overriden equals () method and hashCode () method, the criterion should be consistent two methods, i.e., when the key by two equals ( ) method returns true comparison, the two key hashCode () method returns a value should be the same.

Similar to the HashSet, try not to use a variable object as HashMap of key, if using, then try not to modify the object as a key variable in the program.

LinkedHashMap implementation class

LinkedHashMap also use a doubly linked list to maintain the order of key-value pairs (actually only need to consider the order of the key), which is responsible for maintaining the list iteration order Map of iteration order consistent with the key-value pair insertion order.

import java.util.LinkedHashMap;

public class LinkedHashMapTest {
    public static void main(String[] args) {
        LinkedHashMap scores = new LinkedHashMap();
        scores.put("Chinses", 80);
        scores.put("English", 82);
        scores.put("Math", 76);
        scores.forEach((key ,value) -> System.out.println(key + "--->" + value));
    }
}

TreeMap implementation class

TreeMap is a red-black tree data structure, i.e., each key-value pairs as a red-black tree node. TreeMap stored key-value pairs node, nodes need to sort key. TreeMap can ensure that all key-value pairs in an orderly state.

Two kinds Sort by:

  • Natural order: All key TreeMap must implement the Comparable interface, and all the key should be the object of the same class, otherwise it will throw ClassCastException.
  • Custom sort: When you create a TreeMap, pass a Comparator object, which is responsible for all key TreeMap is sorted. Map is not required when using a custom sort key implement the Comparable interface

TreeMap determination is equal to two key criteria: 0 by two key returns compareTo method.

Like TreeSet, we should maintain consistent results if you use a custom class as the key TreeMap, in order to allow TreeMap good work, the kind of rewriting equals () method and compareTo () method: comparison of two key equals method return true, comparing them by compareTo method should return 0.

When implementing compareTo method, it is strongly recommended consistent with equals results, otherwise some strange errors may occur. The class is because some equals to determine reproducibility, the use of some sort of natural x.compareTo (y) == 0 is determined. compareTo is to determine the position of the element in the sort of equality, equals is to determine whether the same element, since a decision ordering position, a decision are equal, so we need to ensure the very same position when ordering, which equals should be equal.

Official Documentation:

Virtually all Java core classes that implement Comparable have natural orderings that are consistent with equals.

EnumMap implementation class

The key must be EnumMap single enumeration class enumeration value.

EnumMap has the following characteristics:

  • EnumMap is stored internally as an array

  • The key EnumMap natural sequence (i.e., sequence of enumerated values ​​in the enumeration class) to maintain the order of the key-value pairs

  • EnumMap key value is not null as

You must specify an enumeration when you create a class EnumMap, and thus the EnumMap specified enumerated classes associated.

I welcome the attention of the public number

Guess you like

Origin www.cnblogs.com/Tianny/p/11619659.html