day07

持有对象

11.1泛型和类型安全的容器

11.2基本概念

  1. Collection.一个独立元素的序列,这些元素都服从一条或多条规则.
  2. Map.一组成对的"键值对"对象,允许你使用键来查找值.
  3. 注意:在使用时,创建一个具体类的对象,将其转型为对应的接口,然后在其余的代码中都使用和这个接口,这种方式并非总能奏效,因为这些类具有额外的功能.

11.3添加一组元素

  1. Arrays.asList()方法接受一个数组或是一个用逗号分割的元素列表(使用可变参数),并将其转换为一个List对象.Collections.addAll()方法接收一个Collection对象,以及一个数组或是一个用逗号分割的列表,将元素添加到Collection中.
  2. Collection可以接收另一个Collection,用它来将自身初始化,可以用ArrayList()来为这个构造器产生输入.但是Collection.addAll()方法运行起来要快的多,而且构建一个不包含元素的Collection,然后调用Collections.addAll()这种方式很方便,因此它是首选方式.(因为Collection.addAll()成员方法只能接收另一个Collection对象作为参数,因此他不如Arrays.asList或Collection.addAll()灵活(可选列表))
  3. 当直接使用Arrays.asList()的输出,将其当作List,这样的底层表示的数组,不能调整尺寸.
public class AddingGroups {
    public static void main(String[] args) {
        Collection collection = new ArrayList(Arrays.asList(1,2,3,4,5));
        Integer[] moreInts = {6,7,8,9,10};
        collection.addAll(Arrays.asList(moreInts));
        //Runs significantly faster ,but you can't
        //construct a Collection this way
        Collections.addAll(collection,11,12,13,14,15);
        Collections.addAll(collection,moreInts);
        //Produces a list "backed by" an array
        //重点
        List list = Arrays.asList(16,17,18,19,20);//返回一个ArrayList对象
        list.set(1,99);//OK --modify an element
        //list.add(21);//Runtime error because the
        //underlying array cannot be resized
        for (Integer i :
                collection) {
            System.out.print(i + " ");
        }
        for (Integer i :
                list) {
            System.out.print(i + " ");
        }
    }
}
  1. 再来谈一谈我们的Arrays.asList()方法

[图片上传失败...(image-b15d75-1535024738899)].png)

[图片上传失败...(image-6f9144-1535024738899)]

class Snow{}
class Powder extends  Snow{}
class Light extends Powder{}
class Heavy extends Powder{}
class Crusty extends Snow{}
class Slush extends Snow{}
public class AsListInference {
    public static void main(String[] args) {
        List snowl = Arrays.asList(new Crusty(),new Slush(),new Powder());//公共直接类型为Snow共同的父类so能行
        //Won't compile;
        //List snow2 = Arrays.asList(
        // new Light(),new Heavy());//共同的父类为Powder而不是Snow
        //Compiler says;
        //found    : java.util.List
        //required: java.util .List
        //Collections.addAll() doesn't get confused:
        List snow3 = new ArrayList();
        Collections.addAll(snow3,new Light(),new Heavy());

        //Give a hint using an
        //explicit type argument specification:
        List snow4 = Arrays.asList(new Light(),new Heavy());
    }
}

本章中重要的API以及个人理解

Arrays注意里面都是静态方法用Arrays类名调用

This class contains various methods for manipulating arrays such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists.

  • Arrays.asList()已经剖析完毕不需再进行分析
  • Arrays.toString(基本数据类型[]或者object[])不如说对象或者基本数据类型如果把基本数据类型变为object的别名那么也行.

Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space). Elements are converted to strings as by String.valueOf(基本数据类型或者object). Returns "null" if a is null.

  • Arrays.binarySearch(T[],key)

Searches the specified array of bytes for the specified value using the binary search algorithm. The array must be sorted (as by the sort(object[]) method) prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found.

  • Arrays.equals(object[]a,object[]a2)

Returns true if the two specified arrays of Objects are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. Also, two array references are considered equal if both are null.
[图片上传失败...(image-974ba9-1535024738899)]

那么我们再次寻找Objects的equals的调用方式

[图片上传失败...(image-159211-1535024738899)]

再调用Object的equals方法

[图片上传失败...(image-a9a595-1535024738899)]

  • Arrays.fill(Object[] a, Object val)

Assigns the specified Object reference to each element of the specified array of Objects.
Parameters:
a - the array to be filled
val - the value to be stored in all elements of the array

  • Arrays.sort(Object[] a)

Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. All elements in the array must implement the Comparable interface. Furthermore, all elements in the array must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array).

Collections工具类也也只有静态方法

This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, and a few other odds and ends.

  • public static boolean addAll(Collection c, T... elements)

Adds all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array. The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations.

  • public static void shuffle(List list)

Randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood.

List

All Superinterfaces: Collection,Iterable
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

  • Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

  • The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience.

  • The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

  • The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

  • The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.

  • The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

  • Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.

  • Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.

  • List subList(int fromIndex,int toIndex)

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.)

  • void add(int index,E element)

Inserts the specified element at the specified position in this list (optional operation). Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

Iterator

[图片上传失败...(image-7d87ae-1535024738899)]

An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways:
Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
Method names have been improved.

  • boolean hasNext()

Returns true if the iteration has more elements. (In other words, returns true if next() would return an element rather than throwing an exception.)

  • E next()

Returns the next element in the iteration

  • void remove()

Removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next(). The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

  • Iterator iterator()

Returns an iterator over the elements in this collection. There are no guarantees concerning the order in which the elements are returned (unless this collection is an instance of some class that provides a guarantee).

Set

Set具有与Collection完全一样的接口,因此没有任何额外功能.实际上Set就是Collection只是行为不同(这是继承与多态思想的典型应用:表现不同的行为)

  • A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

  • The Set interface places additional stipulations, beyond those inherited from the Collection interface, on the contracts of all constructors and on the contracts of the add, equals and hashCode methods. Declarations for other inherited methods are also included here for convenience. (The specifications accompanying these declarations have been tailored to the Set interface, but they do not contain any additional stipulations.)

  • The additional stipulation on constructors is, not surprisingly, that all constructors must create a set that contains no duplicate elements (as defined above).

Map

  • An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

  • This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface.

  • The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.

  • Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a map.

  • All general-purpose map implementation classes should provide two "standard" constructors: a void (no arguments) constructor which creates an empty map, and a constructor with a single argument of type Map, which creates a new map with the same key-value mappings as its argument. In effect, the latter constructor allows the user to copy any map, producing an equivalent map of the desired class. There is no way to enforce this recommendation (as interfaces cannot contain constructors) but all of the general-purpose map implementations in the JDK comply.

  • The "destructive" methods contained in this interface, that is, the methods that modify the map on which they operate, are specified to throw UnsupportedOperationException if this map does not support the operation. If this is the case, these methods may, but are not required to, throw an UnsupportedOperationException if the invocation would have no effect on the map. For example, invoking the putAll(Map) method on an unmodifiable map may, but is not required to, throw the exception if the map whose mappings are to be "superimposed" is empty.

  • Some map implementations have restrictions on the keys and values they may contain. For example, some implementations prohibit null keys and values, and some have restrictions on the types of their keys. Attempting to insert an ineligible key or value throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible key or value may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible key or value whose completion would not result in the insertion of an ineligible element into the map may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.

  • This interface is a member of the Java Collections Framework.

  • Many methods in Collections Framework interfaces are defined in terms of the equals method. For example, the specification for the containsKey(Object key) method says: "returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null : key.equals(k))." This specification should not be construed to imply that invoking Map.containsKey with a non-null argument key will cause key.equals(k) to be invoked for any key k. Implementations are free to implement optimizations whereby the equals invocation is avoided, for example, by first comparing the hash codes of the two keys. (The Object.hashCode() specification guarantees that two objects with unequal hash codes cannot be equal.) More generally, implementations of the various Collections Framework interfaces are free to take advantage of the specified behavior of underlying Object methods wherever the implementor deems it appropriate.

  • Set keySet()

Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

容器的打印

  1. ArrayList和LinkedList都是List类型,两者的不同之处不仅在于执行某些类型的操作时的性能,而且LinkedList包含的操作也多于ArrayList.

  2. HashSet TreeSet和LinkedHashSet都是Set类型,每个相同的项只保存一次,HashSet使用的是相当复杂的方式来存储元素,是最快的获取元素方式.

  3. 如果存储顺序很重要,那么可以使用TreeSet,它比较结果的升序保存对象;或者使用LinkedHashSet,他按照被添加的顺序保存对象.

  4. HashMap也提供了最快的查找技术,也没有按照任何明显的顺序来保存其元素.TreeMap按照比较结果的升序保存键,而LinkedHashMap则按照插入顺序保存键,同时还保留了HashMap的查询速度.

Foreach与迭代器

  1. foreach与所有的Collection对象都能工作,之所以能够工作,是因为Java引入了新的被称为Iterator的接口,该接口包含一个能够产生Iterator的iterator方法,并且Iterable接口被foreach用来在序列中移动.因此如果你创建了任何实现Iterator的类都可以将它用于foreach语句中.

你可能感兴趣的:(day07)