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 collection is. Let's post a description of the collection.

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 collections (Java. Util. Collection) and double column collections (Java. Util. Map). Let's talk about collection collections 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 other words, the difference between the two sub interfaces 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)`:  把给定的对象添加到当前集合中 。
* `public void clear()` :清空集合中所有的元素。
* `public boolean remove(E e)`: 把给定的对象在当前集合中删除。
* `public boolean contains(E e)`: 判断当前集合中是否包含给定的对象。
* `public boolean isEmpty()`: 判断当前集合是否为空。
* `public int size()`: 返回集合中元素的个数。
* `public Object[] toArray()`: 把集合中的元素,存储到数组中。

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:

Common methods:

public E next():返回迭代的下一个元素。
public boolean hasNext():如果仍有元素可以迭代,则返回 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 of 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 collection, with simple syntax. His internal principle is actually an iterator iterator.

Format:

for(元素的数据类型  变量 : Collection集合or数组){ 
  	...
}

Usually, you only traverse elements, and you can't add or delete them 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:

Classes with generics:

public class Demo11<R> {
    private R r;


    public R getR() {
        return r;
    }

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

main方法代码:

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:

类:

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

    }
}


main方法代码:

    public static void main(String[] args) {

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

    }

Interfaces with generics:

Code example:

Define format:


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

}

实现接口类:

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

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

This 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.

实现类:

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

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

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

main方法代码:

  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 collection. Duplicate elements are allowed in the list interface, which can be accessed by index in the program. The data stored in the list interface is ordered.

public class DemoMain {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("狗子");
        list.add("二狗");
        list.add("狗蛋");

        list.add(1,"狗蛋子");
        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). This is demonstrated by the HashSet implementation class

    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 parameters

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:

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

        method(1,1,1);//使用可变参数方法
        method1(arr);//不使用可变参数方法
    }

    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.

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)  `:往集合中添加一些元素。
- `public static void shuffle(List<?> list) 打乱顺序`:打乱集合顺序。
- `public static <T> void sort(List<T> list)`:将集合中元素按照默认规则排序。
- `public static <T> void sort(List<T> list,Comparator<? super T> )`:将集合中元素按照指定规则排序。

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 look at the most commonly used implementation classes

Hashmap

Methods in the map interface:

public V put(K key,V value) : 把指定的键与指定的值添加到Map集合中。
public V remove(Object key) : 把指定的键 所对应的键值对元素 在Map集合中删除,返回被删除元素的
值。
public V get(Object key) 根据指定的键,在Map集合中获取对应的值。
public Set<K> keySet() : 获取Map集合中所有的键,存储到Set集合中。
public Set<Map.Entry<K,V>> entrySet() : 获取到Map集合中所有的键值对对象的集合(Set集合)

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

code:

public static void main(String[] args) {

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

    }

When using the put method, if the specified key does not exist in the collection, there is no value corresponding to the 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("狗子",18);
    map.put("二狗",17);
    map.put("狗蛋",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 collection, we can obtain the corresponding key and corresponding value from each key value pair (entry) object.

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

public K getKey():获取Entry对象中的键。

public V getValue()`:获取Entry对象中的值。

code:

public static void main(String[] args) {
        // 创建Map集合对象
        HashMap<String,String> map = new HashMap<String,String>();
        // 添加元素到集合
        map.put("狗子","18");
        map.put("狗蛋","17");
        map.put("二狗","16");

        // 获取 所有的 entry对象  entrySet
        Set<Map.Entry<String,String>> entries = map.entrySet();
        for (Map.Entry<String,String> entry : entries) {
            System.out.println(entry); //遍历

            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("狗子","18");
        list.put("二狗","17");
        list.put("狗蛋","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.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>