java Collection - views and wrappers

View - By using views, you can get other objects that implement the Collection-Map interface.An example of this is the keySet of the mapping class.At first glance, it looks like this method creates a new set, fills in all the keys in the map, and returns to the set.However, this is not the case.Instead, the keySet method returns a class object that implements the Set interface, which operates on the original mapping.This collection is the view.

Lightweight Collection Packager

The static method asList of the Arrays class returns a List wrapper that wraps a regular java array, which can be passed to an expected list or set parameter:

package view;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Testview01 {
    public static void main(String[] args) {
        String[] str = new String[10];
        //The object returned here is not an ArrayList.It is a view object with get and access to the underlying arraysetMethod
        List<String> list = Arrays.asList(str);
        list.set(2, "aaa");
        System.out.println(list.get(2));
        //All methods to change the size of an array, such asadd,remove Methods, etc., will throw Unsupported OperationException abnormal
        //list.add("aaa");
        System.out.println(list.size());
        System.out.println("----------I am a dividing line----------");
        //The asList can accept a variable number of parameters
        List<String> names = Arrays.asList("aa", "bb", "cc");
        System.out.println(names);
        //names.add("aaaaaa");You will also get an error for the same reason
        System.out.println(names.size());
        System.out.println("----------I am a dividing line----------");
        List<String> set = Collections.nCopies(100, "default");
        //There is actually only one assignment here, as detailed in jdk
        System.out.println(set.get(0) == set.get(10));
    }
}


This is a jdk source screenshot of the Collections.nCopies() method, which illustrates that it only assigns values once.

Differentiating Collections classes from Collection interfaces

The Collections class contains many useful methods whose parameters and return values are collections; do not confuse with the Collection interface.

//This method returns a view object.This object implementsSetInterface, the returned object implements a set of unmodifiable single elements,
        //Without the overhead of building data structures
        Set singleton = Collections.singleton(names);
        for(Object sets : singleton) {
            System.out.println(sets);

Subrange

package view;

import java.util.Arrays;
import java.util.List;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;

public class TestView02 {
    public static void main(String[] args) {
        String[] str = new String[]{"aa", "dd", "ff", "cc", "qq", "bb"};
        List<String> list = Arrays.asList(str);
        System.out.println(list);
        List group = list.subList(2, 5);
        System.out.println(group);
        System.out.println("----------I am a dividing line----------");
        SortedSet<String> set = new TreeSet<String>(list);
        SortedSet<String> subset = set.subSet("aa", "dd");//Greater than aa less than dd does not contain dd
        System.out.println(subset);
        subset.clear();//Delete the selected item and reflect directly in the original map
        System.out.println(set);

        System.out.println("----------I am a dividing line----------");
        SortedMap<Integer, String> map = new TreeMap<Integer, String>();
        map.put(1, "ff");
        map.put(2, "aa");
        map.put(3, "gg");
        map.put(4, "ee");
        map.put(5, "cc");
        System.out.println(map);
        SortedMap<Integer, String> submap = map.subMap(2, 4);
        System.out.println(submap);
        submap.clear();
        System.out.println(map);
    }
}

Unmodifiable View

Collections also have several methods for generating an unmodifiable view of a collection.These views Add a runtime check to an existing collection.If an attempt is made to modify the collection, an exception is thrown and the collection remains unmodified.
(Reminder again: pay attention to distinguishing Collections from Collections)

There are eight ways to get an unmodifiable view:

Collections.unmodifiableCollection
Collections.unmodifiableList
Collections.unmodifiableSet
Collections.unmodifiableSortedSet
Collections.unmodifiableMap
Collections.unmodifiableSortedMap
Collections.unmodifiableNavigableSet
Collections.unmodifianleNavigableMap
Each method is defined in an interface.For example, Collections.unmodifiableList works with ArrayList, LinkedList, or any other class that implements the List interface;

package view;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class TestView03 {
    public static void main(String[] args) {
        List<String> list = Collections.nCopies(5, "default");
        List view = Collections.unmodifiableList(list);//This method obtains an unmodifiable view
        System.out.println(view.get(0));
        view.add("aaa");//Error, getting non-modifiable view
        System.out.println("----------I am a dividing line----------");
        List<String> staff = new LinkedList<String>();
        lookAt(Collections.unmodifiableList(staff));
    }
}

The Collections.unmodifiableList method returns a class object that implements the List interface.Of course, the lookAt method can call all methods in the List interface, not just accessors.However, all changer methods have been redefined to throw an UnsuportedOperationException exception instead of passing the call to the underlying collection;
Be careful:
A non-modifiable view is not an aggregation that cannot be modified by itself, but the original collection cannot be modified by its projected view.The original collection can still be modified with the original reference to the practical collection.
Since views only wrap interfaces, not actual collection objects, only methods defined in interfaces can be accessed.For example, the LinkedList class has some common methods, addFirst and addLast, which are not List interface methods and cannot be accessed through unmodifiable views.

Synchronize Views

  If the collection is accessed by multiple threads, you must ensure that it is not accidentally destroyed.Class library designers use a view mechanism to ensure thread security for regular collections rather than collections that implement thread security.For example, a static synchronized Map of the Collections class can convert any mapping table into a Map with synchronous access methods:
Map<String, Employee> map = Collections.synchronizedMap(new HashMap<String, Employee>())

View Checked

package view;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class TestView04 {
    public static void main(String[] args) {
        ArrayList<String> str = new ArrayList<String>();
        ArrayList string = str;
        string.add(new Date());//No type mismatch was found here
        Date date = (Date)string.get(0);
        System.out.println(date);

        /*String s = (String) string.get(0);//Type mismatch detected here
        System.out.println(s);*/
        System.out.println("----------I am a dividing line----------");
        ArrayList<String> str2 = new ArrayList<String>();
        List<String>  safe = Collections.checkedList(str2, String.class); 
        List string02 = safe;
        string02.add(new Date());//The compiler did not detect an add exception here
        System.out.println("ok");
    }
}

Keywords: Java JDK less

Added by ILMV on Mon, 17 Jun 2019 19:37:53 +0300