Java – what is a view of a collection?

I've been reading the terminology view while using the guava series and reading its documentation

I have sought an explanation of what opinion it is in this context and whether it is used outside guava This is often used here This type from guava has its name

My guess is that the view of a set is another set with the same data but different structure; For example, when I start from Java util. Add entries to Java. Net in HashSet util. When linkedhashset, the latter will be the view of the former Is that right?

Can someone connect me to the accepted view definition link if there is one?

thank you.

Solution

The view of another object does not contain its own data at all All operations are implemented according to the operation of another object

For example, the keyset () view of map may have the following implementation:

class KeySet implements Set<K> {
  private final Map<K,V> map;

  public boolean contains(Object o) {
    return map.containsKey(o);
  }

  ...
}

In particular, when you modify the view's supporting objects, here the map will return keyset () – the view reflects the same change For example, if you call map Remove (key), then keyset Contains (key) will return false without any other action

Or, arrays Aslist (array) provides a list view of the array

String[] strings = {"a","b","c"};
List<String> list = Arrays.asList(strings);
System.out.println(list.get(0)); // "a"
strings[0] = "d";
System.out.println(list.get(0)); // "d"
list.set(0,"e");
System.out.println(strings[0]); // "e"

View is just another way to view the data in the original support object – arrays Aslist allows you to access normal arrays using the list API; Map. Keyset () allows you to access the keys of the map as if it were a completely normal set – all of this without copying data or creating another data structure

In general, the advantage of using views instead of making copies is efficiency For example, if you have an array and need to get a method to get a list, you won't create a new ArrayList and an entire copy of the data - arrays The aslist view requires only one extra memory and implements all the list methods by accessing the original array

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
分享
二维码
< <上一篇
下一篇>>