Collection of Java learning

Collection of Java learning

0x00 Preface

In fact, the common classes in the previous article have already talked about the ArrayList collection, but ArrayList is only one of the collections. This article will talk about some objects of the collection.

0x01 set concept

Let's first understand what a set is,
Let's post a description of the collection.

Collection: a container in java that can be used to store multiple data.

A concept to be clarified here is that the length of an array is fixed. Once defined, it cannot be renamed, and the set can be changed.

Collections store objects. The types of objects can be different, but arrays can only store basic data types.

Collection architecture

According to the storage structure, collections can be divided into two categories: single column collection (java.util.Collection) and double column collection (java.util.Map). Let's talk about collection collection first.

Collection is the root interface of a single column collection class. It is used to store elements that conform to certain rules. It has two main sub interfaces, namely Java util. List and Java util. Set.

In terms of the difference between the two sub interfaces, the feature of List is that the stored elements are orderly and the elements can be repeated. The characteristic of set is that the elements are out of order and the stored elements cannot be repeated. The main implementation classes of List interface include ArrayList and LinkedList, and the main implementation classes of set interface include HashSet and TreeSet

0x02 Collection

Collection is the parent interface of all single column collections, that is, collection is the top layer of all single column collections. Therefore, some common methods for single column sets (List and Set) are defined in the collection, which can be used to operate all single column sets.

* `public boolean add(E e)`:   Adds the given object to the current collection.
* `public void clear()` :Empty all elements in the collection.
* `public boolean remove(E e)`: Deletes the given object from the current collection.
* `public boolean contains(E e)`: Determines whether the given object is included in the current collection.
* `public boolean isEmpty()`: Judge whether the current collection is empty.
* `public int size()`: Returns the number of elements in the collection.
* `public Object[] toArray()`: Store the elements in the collection into an array.

Use these methods here

public class Input {

    public static void main(String[] args) {
        Collection<String> list = new ArrayList<>();
        list.add("123");
        list.add("321");
        list.remove("123");
        boolean a = list.isEmpty();
        System.out.println(a);
        System.out.println(list);

        
    }
}


0x03 iterator

When we want to traverse, we usually use the for loop. However, when traversing a collection, java provides us with an Iterator interface, that is, an Iterator, which is also a kind of collection.

First, let's understand the concept of iteration:

Collection is a general way to get collection elements. Before taking elements, first judge whether there are elements in the set. If there are, take out this element and continue to judge. If there are any, take it out again. Always take out all the elements in the set. This extraction method is called iteration in technical terms.

Common methods:

public E next():Returns the next element of the iteration.
public boolean hasNext():Returns if there are still elements to iterate over true. 

Code example:

public static void main(String[] args) {
        Collection<String> list = new ArrayList<>();

        list.add("123");
        list.add("321");
        list.add("baidu");
        list.add("google");
        Iterator<String> is = list.iterator();

        while (is.hasNext()){
            String i = is.next();
            System.out.println(i);
        }
    }

The condition for using the while loop here is to judge whether there is a value in the set, and then read the value and assign it to i. The overall code is relatively simple.

0x04 enhanced for loop

The enhanced for loop is the one we use most in traversing the set, with simple syntax. His internal principle is actually an Iterator iterator.

Format:

for(Data type variable of element : Collection aggregate or array){ 
  	...
}

Generally, it only traverses elements, and cannot add or delete in enhanced for.

public static void main(String[] args) {
        Collection<String> list = new ArrayList<>();

        list.add("123");
        list.add("321");
        list.add("baidu");
        list.add("google");

        for (String s : list) {
            System.out.println(s);
            
        }

    }

When you write with IDEA, you will be prompted.

0x05 generic

Generics are unknown data types. We can use generics if we don't know what data types.

Code format:

Modifier class class name < variables representing generics > {}

Classes with generics:

public class Demo11<R> {
    private R r;


    public R getR() {
        return r;
    }

    public void setR(R r) {
        this.r = r;
    }
}

main Method code:

public class DemoMain {
    public static void main(String[] args) {
        Demo11<String> str = new Demo11<>();
        str.setR("123");
        System.out.println(str.getR());
    }

}

Methods with generics:

Class:

    public <R> void method(R r){
        System.out.println(r);

    }
}


main Method code:

    public static void main(String[] args) {

        Demo11 abc = new Demo11();
        abc.method("abc");

    }

When a method is called, the type of the generic type is determined

Interfaces with generics:

Code example:

Define format:

Modifier interface interface name < variables representing generics > {}

public interface MyInterface<R> {
    public abstract void add(R r);
    public abstract R getR();

}

Implementation interface class:

public class MyInterfaceimpl implements MyInterface<String> {
    @Override
    public void add(String s) {
        System.out.println(s);
    }

    @Override
    public String getR() {
        return null;
    }
}

Here is to determine the generic type in the implementation interface.

If the type cannot always be determined, you can also determine the type when creating the object.

Implementation class:

public class MyInterfaceimpl<R> implements MyInterface<R>  {

    @Override
    public void add(R r) {
        System.out.println(r);
    }

    @Override
    public R getR() {
        return null;
    }
}

main Method code:

  public static void main(String[] args) {
        MyInterfaceimpl<String> str = new MyInterfaceimpl<>();
        str.add("123");


    }

When creating the object, it is determined that the type is string.

0x06 List interface

The List interface is a sub interface of the Collection,
Duplicate elements are allowed in the List interface, which can be accessed through index in the program.
The data stored in the List interface is orderly.

public class DemoMain {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Dog");
        list.add("Two dogs");
        list.add("son of a bitch");

        list.add(1,"Dog egg");
        list.remove(1);
        System.out.println(list);
    }
}

0x07 set interface

The set interface also inherits the Collection interface and is a single column Collection.
The elements in the set interface are out of order, and some rules will be used to ensure that the stored elements are not repeated.

The implementation classes of the set interface include:

AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList,Stack, Vector. 

Hashset

The elements stored in Hashset are non repeatable, and the elements are out of order (that is, the access order is inconsistent).
Let's use the hashset implementation class to demonstrate

    public static void main(String[] args) {
        HashSet<String> list = new HashSet<>();

        list.add("123");
        list.add("785");
        list.add(new String("23"));
        for (String s : list) {   System.out.println(s);
        }
    }

LinkHashSet

hashset is to ensure the uniqueness of elements. If you want to order, you need to use LinkedHashSet.

public static void main(String[] args) {

        Set<String> set = new LinkedHashSet<>();

        set.add("123");
        set.add("12");
        set.add("12999");
        set.add("1453");
        set.add("543");
        for (String s : set) {
            System.out.println(s);
        }
    }

Variable parameter

Here is a little knowledge about variable parameters.

If we define a method, we need to accept multiple parameters, and the types of multiple parameters are consistent.

Define format:

Modifier return value type method name (parameter type... Formal parameter name) {}

 public static void main(String[] args) {
        int[] arr = {1,2,3,4};

        method(1,1,1,1);//Using variable parameter method
        method1(arr);//Variable parameter method is not used
    }

    private static void method1(int[] args) {
        for (int arg : args) {
            System.out.println(arg);

        }

    }

    private static void method(int... args) {
        System.out.println(args);
    }

Here you can see two definition methods. One is to use variable parameters, which can directly save the trouble of defining an array first and then passing it in.

Note: if the method has multiple parameters when writing, and the parameters contain variable parameters, the variable parameters must be written at the end of the parameter list.

0x08 collections class

This is different from the collection mentioned earlier. Conection is the interface of a single column collection, and conections is the tool class of the collection.

This class is a static class and can be called directly using the class name.

Common methods:

- public static <T> boolean addAll(Collection<T> c, T... elements)  `:Add some elements to the collection.
- `public static void shuffle(List<?> list) Disorder order`:Disrupt the order of the collection.
- `public static <T> void sort(List<T> list)`:Sorts the elements in the collection according to the default rules.
- `public static <T> void sort(List<T> list´╝îComparator<? super T> )`:Sorts the elements in the collection according to the specified rules.

Code example:

    public static void main(String[] args) {

        ArrayList<Integer> list = new ArrayList<>();

        Collections.addAll(list, 123, 1243, 1354, 123);
        System.out.println(list);
        Collections.sort(list);
        System.out.println(list);
    }

In the past, collections used to add data one by one, but collections can add multiple data at a time.

0x09 Map collection

In some Concordes of collection, elements exist separately. You want to store elements in a collection.
The set elements in the map exist in pairs. Each element consists of a key and a value, and the corresponding value can be found through the key.

Known implementation classes:

AbstractMap, Attributes, AuthProvider, ConcurrentHashMap, ConcurrentSkipListMap, EnumMap, HashMap, Hashtable, IdentityHashMap, LinkedHashMap, PrinterStateReasons, Properties, Provider, RenderingHints, SimpleBindings, TabularDataSupport, TreeMap, UIDefaults, WeakHashMap 

Let's take a look at the most commonly used implementation classes

Hashmap

HashMap: the hash table structure used to store data. The access order of elements cannot be guaranteed to be consistent. To ensure the uniqueness and non repetition of keys, you need to
hashCode() method and equals() method to override the key.

Methods in the map interface:

public V put(K key, V value) : Adds the specified key and the specified value to the Map In the collection.
public V remove(Object key) : Match the key value corresponding to the specified key to the element Map Collection. Returns the of the deleted element
 Value.
public V get(Object key) According to the specified key, in Map Get the corresponding value from the collection.
public Set<K> keySet() : obtain Map All keys in the collection, stored in Set In the collection.
public Set<Map.Entry<K,V>> entrySet() : Get Map A collection of all key value pair objects in the collection(Set aggregate)

The collection in the Map interface has two generic variables. When using, you should assign data types to the two generic variables. Number of two generic variables
The data types can be the same or different.

code:

public static void main(String[] args) {

        HashMap<String, String> map = new HashMap<>();
        map.put("Xiao Ming","18");
        map.put("Small j","48");
        map.put("Small x","88");
        map.put("Small g","98");
        System.out.println(map.get("Xiao Ming"));

    }

When using the put method, if the specified key does not exist in the collection, there is no value corresponding to this key, null is returned, and the specified key value is added to the collection. If the specified key exists in the set, the return value is the value corresponding to the key in the set (the value is the value before replacement), and the value corresponding to the specified key is replaced with the specified new value.

map set traversal

map provides a method keyset to obtain all key values. For our traversal.

public static void main(String[] args) {
    HashMap<String,Integer> map = new HashMap<>();
    map.put("Dog",18);
    map.put("Two dogs",17);
    map.put("son of a bitch",16);


    Set<String> keys = map.keySet();
        for (String key : keys) {
            Integer value = map.get(key);
            System.out.println(value);
        }
    }

Traverse key value pairs

Entry encapsulates the correspondence of key value pairs into objects. That is, the key value pair object, so that when we traverse the Map set, we can obtain the corresponding key and corresponding value from each key value pair object.

Since it is a key value object, it will certainly provide a method to obtain it.

public K getKey(): obtain Entry Object.

public V getValue()`: obtain Entry Object.

code:

public static void main(String[] args) {
        // Create a Map collection object
        HashMap<String, String> map = new HashMap<String,String>();
        // Add element to collection
        map.put("Dog", "18");
        map.put("son of a bitch", "17");
        map.put("Two dogs", "16");

        // Get all entry objects entrySet
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            System.out.println(entry); //ergodic

            System.out.println("key"+entry.getKey());
            System.out.println("value"+entry.getValue());
        }
    }

LinkedHashMap

The storage of Hashmap is out of order. If you need to store data in order, you need to use LinkedHashMap.

public static void main(String[] args) {

        LinkedHashMap<String,String> list = new LinkedHashMap<>();
        list.put("Dog","18");
        list.put("Two dogs","17");
        list.put("son of a bitch","16");
        Set<Map.Entry<String, String>> entries = list.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            System.out.println(entry);
        }
    }

End of 0x10

Some things about the set have also been written. In fact, some data structures of the set have not been written in. I plan to extract the data structure separately and write an article.

Tags: Java

Posted by samsunnyuk on Tue, 24 May 2022 20:40:44 +0300