众所周知,default是java的关键字之一,使用场景是配合switch关键字用于条件分支的默认项。但自从java的jdk1.8横空出世以后,它就被赋予了另一项很酷的能力——在接口中定义非抽象方法。

  众所周知,java的接口只能定义静态且不可变的常量或者公共抽象方法,不可能定义非抽象的具体方法。但自从jdk1.8横空出世以后,它就被default关键字赋予了另一项很酷的能力——在接口中定义非抽象方法。好了不废话了,看具体例子吧:

  1、父接口Iterable,定义了两个default方法forEach和spliterator:

  1. /*
  2. * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  3. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  4. *
  5. *
  6. *
  7. *
  8. *
  9. *
  10. *
  11. *
  12. *
  13. *
  14. *
  15. *
  16. *
  17. *
  18. *
  19. *
  20. *
  21. *
  22. *
  23. *
  24. */
  25. package java.lang;
  26.  
  27. import java.util.Iterator;
  28. import java.util.Objects;
  29. import java.util.Spliterator;
  30. import java.util.Spliterators;
  31. import java.util.function.Consumer;
  32.  
  33. /**
  34. * Implementing this interface allows an object to be the target of
  35. * the "for-each loop" statement. See
  36. * <strong>
  37. * <a href="{@docRoot}/../technotes/guides/language/foreach.html">For-each Loop</a>
  38. * </strong>
  39. *
  40. * @param <T> the type of elements returned by the iterator
  41. *
  42. * @since 1.5
  43. * @jls 14.14.2 The enhanced for statement
  44. */
  45. public interface Iterable<T> {
  46. /**
  47. * Returns an iterator over elements of type {@code T}.
  48. *
  49. * @return an Iterator.
  50. */
  51. Iterator<T> iterator();
  52.  
  53. /**
  54. * Performs the given action for each element of the {@code Iterable}
  55. * until all elements have been processed or the action throws an
  56. * exception. Unless otherwise specified by the implementing class,
  57. * actions are performed in the order of iteration (if an iteration order
  58. * is specified). Exceptions thrown by the action are relayed to the
  59. * caller.
  60. *
  61. * @implSpec
  62. * <p>The default implementation behaves as if:
  63. * <pre>{@code
  64. * for (T t : this)
  65. * action.accept(t);
  66. * }</pre>
  67. *
  68. * @param action The action to be performed for each element
  69. * @throws NullPointerException if the specified action is null
  70. * @since 1.8
  71. */
  72. default void forEach(Consumer<? super T> action) {
  73. Objects.requireNonNull(action);
  74. for (T t : this) {
  75. action.accept(t);
  76. }
  77. }
  78.  
  79. /**
  80. * Creates a {@link Spliterator} over the elements described by this
  81. * {@code Iterable}.
  82. *
  83. * @implSpec
  84. * The default implementation creates an
  85. * <em><a href="Spliterator.html#binding">early-binding</a></em>
  86. * spliterator from the iterable's {@code Iterator}. The spliterator
  87. * inherits the <em>fail-fast</em> properties of the iterable's iterator.
  88. *
  89. * @implNote
  90. * The default implementation should usually be overridden. The
  91. * spliterator returned by the default implementation has poor splitting
  92. * capabilities, is unsized, and does not report any spliterator
  93. * characteristics. Implementing classes can nearly always provide a
  94. * better implementation.
  95. *
  96. * @return a {@code Spliterator} over the elements described by this
  97. * {@code Iterable}.
  98. * @since 1.8
  99. */
  100. default Spliterator<T> spliterator() {
  101. return Spliterators.spliteratorUnknownSize(iterator(), 0);
  102. }
  103. }

  2、子接口复写了spliterator方法

  1. /*
  2. * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  3. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  4. *
  5. *
  6. *
  7. *
  8. *
  9. *
  10. *
  11. *
  12. *
  13. *
  14. *
  15. *
  16. *
  17. *
  18. *
  19. *
  20. *
  21. *
  22. *
  23. *
  24. */
  25.  
  26. package java.util;
  27.  
  28. import java.util.function.Predicate;
  29. import java.util.stream.Stream;
  30. import java.util.stream.StreamSupport;
  31.  
  32. /**
  33. * The root interface in the <i>collection hierarchy</i>. A collection
  34. * represents a group of objects, known as its <i>elements</i>. Some
  35. * collections allow duplicate elements and others do not. Some are ordered
  36. * and others unordered. The JDK does not provide any <i>direct</i>
  37. * implementations of this interface: it provides implementations of more
  38. * specific subinterfaces like <tt>Set</tt> and <tt>List</tt>. This interface
  39. * is typically used to pass collections around and manipulate them where
  40. * maximum generality is desired.
  41. *
  42. * <p><i>Bags</i> or <i>multisets</i> (unordered collections that may contain
  43. * duplicate elements) should implement this interface directly.
  44. *
  45. * <p>All general-purpose <tt>Collection</tt> implementation classes (which
  46. * typically implement <tt>Collection</tt> indirectly through one of its
  47. * subinterfaces) should provide two "standard" constructors: a void (no
  48. * arguments) constructor, which creates an empty collection, and a
  49. * constructor with a single argument of type <tt>Collection</tt>, which
  50. * creates a new collection with the same elements as its argument. In
  51. * effect, the latter constructor allows the user to copy any collection,
  52. * producing an equivalent collection of the desired implementation type.
  53. * There is no way to enforce this convention (as interfaces cannot contain
  54. * constructors) but all of the general-purpose <tt>Collection</tt>
  55. * implementations in the Java platform libraries comply.
  56. *
  57. * <p>The "destructive" methods contained in this interface, that is, the
  58. * methods that modify the collection on which they operate, are specified to
  59. * throw <tt>UnsupportedOperationException</tt> if this collection does not
  60. * support the operation. If this is the case, these methods may, but are not
  61. * required to, throw an <tt>UnsupportedOperationException</tt> if the
  62. * invocation would have no effect on the collection. For example, invoking
  63. * the {@link #addAll(Collection)} method on an unmodifiable collection may,
  64. * but is not required to, throw the exception if the collection to be added
  65. * is empty.
  66. *
  67. * <p><a name="optional-restrictions">
  68. * Some collection implementations have restrictions on the elements that
  69. * they may contain.</a> For example, some implementations prohibit null elements,
  70. * and some have restrictions on the types of their elements. Attempting to
  71. * add an ineligible element throws an unchecked exception, typically
  72. * <tt>NullPointerException</tt> or <tt>ClassCastException</tt>. Attempting
  73. * to query the presence of an ineligible element may throw an exception,
  74. * or it may simply return false; some implementations will exhibit the former
  75. * behavior and some will exhibit the latter. More generally, attempting an
  76. * operation on an ineligible element whose completion would not result in
  77. * the insertion of an ineligible element into the collection may throw an
  78. * exception or it may succeed, at the option of the implementation.
  79. * Such exceptions are marked as "optional" in the specification for this
  80. * interface.
  81. *
  82. * <p>It is up to each collection to determine its own synchronization
  83. * policy. In the absence of a stronger guarantee by the
  84. * implementation, undefined behavior may result from the invocation
  85. * of any method on a collection that is being mutated by another
  86. * thread; this includes direct invocations, passing the collection to
  87. * a method that might perform invocations, and using an existing
  88. * iterator to examine the collection.
  89. *
  90. * <p>Many methods in Collections Framework interfaces are defined in
  91. * terms of the {@link Object#equals(Object) equals} method. For example,
  92. * the specification for the {@link #contains(Object) contains(Object o)}
  93. * method says: "returns <tt>true</tt> if and only if this collection
  94. * contains at least one element <tt>e</tt> such that
  95. * <tt>(o==null ? e==null : o.equals(e))</tt>." This specification should
  96. * <i>not</i> be construed to imply that invoking <tt>Collection.contains</tt>
  97. * with a non-null argument <tt>o</tt> will cause <tt>o.equals(e)</tt> to be
  98. * invoked for any element <tt>e</tt>. Implementations are free to implement
  99. * optimizations whereby the <tt>equals</tt> invocation is avoided, for
  100. * example, by first comparing the hash codes of the two elements. (The
  101. * {@link Object#hashCode()} specification guarantees that two objects with
  102. * unequal hash codes cannot be equal.) More generally, implementations of
  103. * the various Collections Framework interfaces are free to take advantage of
  104. * the specified behavior of underlying {@link Object} methods wherever the
  105. * implementor deems it appropriate.
  106. *
  107. * <p>Some collection operations which perform recursive traversal of the
  108. * collection may fail with an exception for self-referential instances where
  109. * the collection directly or indirectly contains itself. This includes the
  110. * {@code clone()}, {@code equals()}, {@code hashCode()} and {@code toString()}
  111. * methods. Implementations may optionally handle the self-referential scenario,
  112. * however most current implementations do not do so.
  113. *
  114. * <p>This interface is a member of the
  115. * <a href="{@docRoot}/../technotes/guides/collections/index.html">
  116. * Java Collections Framework</a>.
  117. *
  118. * @implSpec
  119. * The default method implementations (inherited or otherwise) do not apply any
  120. * synchronization protocol. If a {@code Collection} implementation has a
  121. * specific synchronization protocol, then it must override default
  122. * implementations to apply that protocol.
  123. *
  124. * @param <E> the type of elements in this collection
  125. *
  126. * @author Josh Bloch
  127. * @author Neal Gafter
  128. * @see Set
  129. * @see List
  130. * @see Map
  131. * @see SortedSet
  132. * @see SortedMap
  133. * @see HashSet
  134. * @see TreeSet
  135. * @see ArrayList
  136. * @see LinkedList
  137. * @see Vector
  138. * @see Collections
  139. * @see Arrays
  140. * @see AbstractCollection
  141. * @since 1.2
  142. */
  143.  
  144. public interface Collection<E> extends Iterable<E> {
  145. // Query Operations
  146.  
  147. /**
  148. * Returns the number of elements in this collection. If this collection
  149. * contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
  150. * <tt>Integer.MAX_VALUE</tt>.
  151. *
  152. * @return the number of elements in this collection
  153. */
  154. int size();
  155.  
  156. /**
  157. * Returns <tt>true</tt> if this collection contains no elements.
  158. *
  159. * @return <tt>true</tt> if this collection contains no elements
  160. */
  161. boolean isEmpty();
  162.  
  163. /**
  164. * Returns <tt>true</tt> if this collection contains the specified element.
  165. * More formally, returns <tt>true</tt> if and only if this collection
  166. * contains at least one element <tt>e</tt> such that
  167. * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
  168. *
  169. * @param o element whose presence in this collection is to be tested
  170. * @return <tt>true</tt> if this collection contains the specified
  171. * element
  172. * @throws ClassCastException if the type of the specified element
  173. * is incompatible with this collection
  174. * (<a href="#optional-restrictions">optional</a>)
  175. * @throws NullPointerException if the specified element is null and this
  176. * collection does not permit null elements
  177. * (<a href="#optional-restrictions">optional</a>)
  178. */
  179. boolean contains(Object o);
  180.  
  181. /**
  182. * Returns an iterator over the elements in this collection. There are no
  183. * guarantees concerning the order in which the elements are returned
  184. * (unless this collection is an instance of some class that provides a
  185. * guarantee).
  186. *
  187. * @return an <tt>Iterator</tt> over the elements in this collection
  188. */
  189. Iterator<E> iterator();
  190.  
  191. /**
  192. * Returns an array containing all of the elements in this collection.
  193. * If this collection makes any guarantees as to what order its elements
  194. * are returned by its iterator, this method must return the elements in
  195. * the same order.
  196. *
  197. * <p>The returned array will be "safe" in that no references to it are
  198. * maintained by this collection. (In other words, this method must
  199. * allocate a new array even if this collection is backed by an array).
  200. * The caller is thus free to modify the returned array.
  201. *
  202. * <p>This method acts as bridge between array-based and collection-based
  203. * APIs.
  204. *
  205. * @return an array containing all of the elements in this collection
  206. */
  207. Object[] toArray();
  208.  
  209. /**
  210. * Returns an array containing all of the elements in this collection;
  211. * the runtime type of the returned array is that of the specified array.
  212. * If the collection fits in the specified array, it is returned therein.
  213. * Otherwise, a new array is allocated with the runtime type of the
  214. * specified array and the size of this collection.
  215. *
  216. * <p>If this collection fits in the specified array with room to spare
  217. * (i.e., the array has more elements than this collection), the element
  218. * in the array immediately following the end of the collection is set to
  219. * <tt>null</tt>. (This is useful in determining the length of this
  220. * collection <i>only</i> if the caller knows that this collection does
  221. * not contain any <tt>null</tt> elements.)
  222. *
  223. * <p>If this collection makes any guarantees as to what order its elements
  224. * are returned by its iterator, this method must return the elements in
  225. * the same order.
  226. *
  227. * <p>Like the {@link #toArray()} method, this method acts as bridge between
  228. * array-based and collection-based APIs. Further, this method allows
  229. * precise control over the runtime type of the output array, and may,
  230. * under certain circumstances, be used to save allocation costs.
  231. *
  232. * <p>Suppose <tt>x</tt> is a collection known to contain only strings.
  233. * The following code can be used to dump the collection into a newly
  234. * allocated array of <tt>String</tt>:
  235. *
  236. * <pre>
  237. * String[] y = x.toArray(new String[0]);</pre>
  238. *
  239. * Note that <tt>toArray(new Object[0])</tt> is identical in function to
  240. * <tt>toArray()</tt>.
  241. *
  242. * @param <T> the runtime type of the array to contain the collection
  243. * @param a the array into which the elements of this collection are to be
  244. * stored, if it is big enough; otherwise, a new array of the same
  245. * runtime type is allocated for this purpose.
  246. * @return an array containing all of the elements in this collection
  247. * @throws ArrayStoreException if the runtime type of the specified array
  248. * is not a supertype of the runtime type of every element in
  249. * this collection
  250. * @throws NullPointerException if the specified array is null
  251. */
  252. <T> T[] toArray(T[] a);
  253.  
  254. // Modification Operations
  255.  
  256. /**
  257. * Ensures that this collection contains the specified element (optional
  258. * operation). Returns <tt>true</tt> if this collection changed as a
  259. * result of the call. (Returns <tt>false</tt> if this collection does
  260. * not permit duplicates and already contains the specified element.)<p>
  261. *
  262. * Collections that support this operation may place limitations on what
  263. * elements may be added to this collection. In particular, some
  264. * collections will refuse to add <tt>null</tt> elements, and others will
  265. * impose restrictions on the type of elements that may be added.
  266. * Collection classes should clearly specify in their documentation any
  267. * restrictions on what elements may be added.<p>
  268. *
  269. * If a collection refuses to add a particular element for any reason
  270. * other than that it already contains the element, it <i>must</i> throw
  271. * an exception (rather than returning <tt>false</tt>). This preserves
  272. * the invariant that a collection always contains the specified element
  273. * after this call returns.
  274. *
  275. * @param e element whose presence in this collection is to be ensured
  276. * @return <tt>true</tt> if this collection changed as a result of the
  277. * call
  278. * @throws UnsupportedOperationException if the <tt>add</tt> operation
  279. * is not supported by this collection
  280. * @throws ClassCastException if the class of the specified element
  281. * prevents it from being added to this collection
  282. * @throws NullPointerException if the specified element is null and this
  283. * collection does not permit null elements
  284. * @throws IllegalArgumentException if some property of the element
  285. * prevents it from being added to this collection
  286. * @throws IllegalStateException if the element cannot be added at this
  287. * time due to insertion restrictions
  288. */
  289. boolean add(E e);
  290.  
  291. /**
  292. * Removes a single instance of the specified element from this
  293. * collection, if it is present (optional operation). More formally,
  294. * removes an element <tt>e</tt> such that
  295. * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>, if
  296. * this collection contains one or more such elements. Returns
  297. * <tt>true</tt> if this collection contained the specified element (or
  298. * equivalently, if this collection changed as a result of the call).
  299. *
  300. * @param o element to be removed from this collection, if present
  301. * @return <tt>true</tt> if an element was removed as a result of this call
  302. * @throws ClassCastException if the type of the specified element
  303. * is incompatible with this collection
  304. * (<a href="#optional-restrictions">optional</a>)
  305. * @throws NullPointerException if the specified element is null and this
  306. * collection does not permit null elements
  307. * (<a href="#optional-restrictions">optional</a>)
  308. * @throws UnsupportedOperationException if the <tt>remove</tt> operation
  309. * is not supported by this collection
  310. */
  311. boolean remove(Object o);
  312.  
  313. // Bulk Operations
  314.  
  315. /**
  316. * Returns <tt>true</tt> if this collection contains all of the elements
  317. * in the specified collection.
  318. *
  319. * @param c collection to be checked for containment in this collection
  320. * @return <tt>true</tt> if this collection contains all of the elements
  321. * in the specified collection
  322. * @throws ClassCastException if the types of one or more elements
  323. * in the specified collection are incompatible with this
  324. * collection
  325. * (<a href="#optional-restrictions">optional</a>)
  326. * @throws NullPointerException if the specified collection contains one
  327. * or more null elements and this collection does not permit null
  328. * elements
  329. * (<a href="#optional-restrictions">optional</a>),
  330. * or if the specified collection is null.
  331. * @see #contains(Object)
  332. */
  333. boolean containsAll(Collection<?> c);
  334.  
  335. /**
  336. * Adds all of the elements in the specified collection to this collection
  337. * (optional operation). The behavior of this operation is undefined if
  338. * the specified collection is modified while the operation is in progress.
  339. * (This implies that the behavior of this call is undefined if the
  340. * specified collection is this collection, and this collection is
  341. * nonempty.)
  342. *
  343. * @param c collection containing elements to be added to this collection
  344. * @return <tt>true</tt> if this collection changed as a result of the call
  345. * @throws UnsupportedOperationException if the <tt>addAll</tt> operation
  346. * is not supported by this collection
  347. * @throws ClassCastException if the class of an element of the specified
  348. * collection prevents it from being added to this collection
  349. * @throws NullPointerException if the specified collection contains a
  350. * null element and this collection does not permit null elements,
  351. * or if the specified collection is null
  352. * @throws IllegalArgumentException if some property of an element of the
  353. * specified collection prevents it from being added to this
  354. * collection
  355. * @throws IllegalStateException if not all the elements can be added at
  356. * this time due to insertion restrictions
  357. * @see #add(Object)
  358. */
  359. boolean addAll(Collection<? extends E> c);
  360.  
  361. /**
  362. * Removes all of this collection's elements that are also contained in the
  363. * specified collection (optional operation). After this call returns,
  364. * this collection will contain no elements in common with the specified
  365. * collection.
  366. *
  367. * @param c collection containing elements to be removed from this collection
  368. * @return <tt>true</tt> if this collection changed as a result of the
  369. * call
  370. * @throws UnsupportedOperationException if the <tt>removeAll</tt> method
  371. * is not supported by this collection
  372. * @throws ClassCastException if the types of one or more elements
  373. * in this collection are incompatible with the specified
  374. * collection
  375. * (<a href="#optional-restrictions">optional</a>)
  376. * @throws NullPointerException if this collection contains one or more
  377. * null elements and the specified collection does not support
  378. * null elements
  379. * (<a href="#optional-restrictions">optional</a>),
  380. * or if the specified collection is null
  381. * @see #remove(Object)
  382. * @see #contains(Object)
  383. */
  384. boolean removeAll(Collection<?> c);
  385.  
  386. /**
  387. * Removes all of the elements of this collection that satisfy the given
  388. * predicate. Errors or runtime exceptions thrown during iteration or by
  389. * the predicate are relayed to the caller.
  390. *
  391. * @implSpec
  392. * The default implementation traverses all elements of the collection using
  393. * its {@link #iterator}. Each matching element is removed using
  394. * {@link Iterator#remove()}. If the collection's iterator does not
  395. * support removal then an {@code UnsupportedOperationException} will be
  396. * thrown on the first matching element.
  397. *
  398. * @param filter a predicate which returns {@code true} for elements to be
  399. * removed
  400. * @return {@code true} if any elements were removed
  401. * @throws NullPointerException if the specified filter is null
  402. * @throws UnsupportedOperationException if elements cannot be removed
  403. * from this collection. Implementations may throw this exception if a
  404. * matching element cannot be removed or if, in general, removal is not
  405. * supported.
  406. * @since 1.8
  407. */
  408. default boolean removeIf(Predicate<? super E> filter) {
  409. Objects.requireNonNull(filter);
  410. boolean removed = false;
  411. final Iterator<E> each = iterator();
  412. while (each.hasNext()) {
  413. if (filter.test(each.next())) {
  414. each.remove();
  415. removed = true;
  416. }
  417. }
  418. return removed;
  419. }
  420.  
  421. /**
  422. * Retains only the elements in this collection that are contained in the
  423. * specified collection (optional operation). In other words, removes from
  424. * this collection all of its elements that are not contained in the
  425. * specified collection.
  426. *
  427. * @param c collection containing elements to be retained in this collection
  428. * @return <tt>true</tt> if this collection changed as a result of the call
  429. * @throws UnsupportedOperationException if the <tt>retainAll</tt> operation
  430. * is not supported by this collection
  431. * @throws ClassCastException if the types of one or more elements
  432. * in this collection are incompatible with the specified
  433. * collection
  434. * (<a href="#optional-restrictions">optional</a>)
  435. * @throws NullPointerException if this collection contains one or more
  436. * null elements and the specified collection does not permit null
  437. * elements
  438. * (<a href="#optional-restrictions">optional</a>),
  439. * or if the specified collection is null
  440. * @see #remove(Object)
  441. * @see #contains(Object)
  442. */
  443. boolean retainAll(Collection<?> c);
  444.  
  445. /**
  446. * Removes all of the elements from this collection (optional operation).
  447. * The collection will be empty after this method returns.
  448. *
  449. * @throws UnsupportedOperationException if the <tt>clear</tt> operation
  450. * is not supported by this collection
  451. */
  452. void clear();
  453.  
  454. // Comparison and hashing
  455.  
  456. /**
  457. * Compares the specified object with this collection for equality. <p>
  458. *
  459. * While the <tt>Collection</tt> interface adds no stipulations to the
  460. * general contract for the <tt>Object.equals</tt>, programmers who
  461. * implement the <tt>Collection</tt> interface "directly" (in other words,
  462. * create a class that is a <tt>Collection</tt> but is not a <tt>Set</tt>
  463. * or a <tt>List</tt>) must exercise care if they choose to override the
  464. * <tt>Object.equals</tt>. It is not necessary to do so, and the simplest
  465. * course of action is to rely on <tt>Object</tt>'s implementation, but
  466. * the implementor may wish to implement a "value comparison" in place of
  467. * the default "reference comparison." (The <tt>List</tt> and
  468. * <tt>Set</tt> interfaces mandate such value comparisons.)<p>
  469. *
  470. * The general contract for the <tt>Object.equals</tt> method states that
  471. * equals must be symmetric (in other words, <tt>a.equals(b)</tt> if and
  472. * only if <tt>b.equals(a)</tt>). The contracts for <tt>List.equals</tt>
  473. * and <tt>Set.equals</tt> state that lists are only equal to other lists,
  474. * and sets to other sets. Thus, a custom <tt>equals</tt> method for a
  475. * collection class that implements neither the <tt>List</tt> nor
  476. * <tt>Set</tt> interface must return <tt>false</tt> when this collection
  477. * is compared to any list or set. (By the same logic, it is not possible
  478. * to write a class that correctly implements both the <tt>Set</tt> and
  479. * <tt>List</tt> interfaces.)
  480. *
  481. * @param o object to be compared for equality with this collection
  482. * @return <tt>true</tt> if the specified object is equal to this
  483. * collection
  484. *
  485. * @see Object#equals(Object)
  486. * @see Set#equals(Object)
  487. * @see List#equals(Object)
  488. */
  489. boolean equals(Object o);
  490.  
  491. /**
  492. * Returns the hash code value for this collection. While the
  493. * <tt>Collection</tt> interface adds no stipulations to the general
  494. * contract for the <tt>Object.hashCode</tt> method, programmers should
  495. * take note that any class that overrides the <tt>Object.equals</tt>
  496. * method must also override the <tt>Object.hashCode</tt> method in order
  497. * to satisfy the general contract for the <tt>Object.hashCode</tt> method.
  498. * In particular, <tt>c1.equals(c2)</tt> implies that
  499. * <tt>c1.hashCode()==c2.hashCode()</tt>.
  500. *
  501. * @return the hash code value for this collection
  502. *
  503. * @see Object#hashCode()
  504. * @see Object#equals(Object)
  505. */
  506. int hashCode();
  507.  
  508. /**
  509. * Creates a {@link Spliterator} over the elements in this collection.
  510. *
  511. * Implementations should document characteristic values reported by the
  512. * spliterator. Such characteristic values are not required to be reported
  513. * if the spliterator reports {@link Spliterator#SIZED} and this collection
  514. * contains no elements.
  515. *
  516. * <p>The default implementation should be overridden by subclasses that
  517. * can return a more efficient spliterator. In order to
  518. * preserve expected laziness behavior for the {@link #stream()} and
  519. * {@link #parallelStream()}} methods, spliterators should either have the
  520. * characteristic of {@code IMMUTABLE} or {@code CONCURRENT}, or be
  521. * <em><a href="Spliterator.html#binding">late-binding</a></em>.
  522. * If none of these is practical, the overriding class should describe the
  523. * spliterator's documented policy of binding and structural interference,
  524. * and should override the {@link #stream()} and {@link #parallelStream()}
  525. * methods to create streams using a {@code Supplier} of the spliterator,
  526. * as in:
  527. * <pre>{@code
  528. * Stream<E> s = StreamSupport.stream(() -> spliterator(), spliteratorCharacteristics)
  529. * }</pre>
  530. * <p>These requirements ensure that streams produced by the
  531. * {@link #stream()} and {@link #parallelStream()} methods will reflect the
  532. * contents of the collection as of initiation of the terminal stream
  533. * operation.
  534. *
  535. * @implSpec
  536. * The default implementation creates a
  537. * <em><a href="Spliterator.html#binding">late-binding</a></em> spliterator
  538. * from the collections's {@code Iterator}. The spliterator inherits the
  539. * <em>fail-fast</em> properties of the collection's iterator.
  540. * <p>
  541. * The created {@code Spliterator} reports {@link Spliterator#SIZED}.
  542. *
  543. * @implNote
  544. * The created {@code Spliterator} additionally reports
  545. * {@link Spliterator#SUBSIZED}.
  546. *
  547. * <p>If a spliterator covers no elements then the reporting of additional
  548. * characteristic values, beyond that of {@code SIZED} and {@code SUBSIZED},
  549. * does not aid clients to control, specialize or simplify computation.
  550. * However, this does enable shared use of an immutable and empty
  551. * spliterator instance (see {@link Spliterators#emptySpliterator()}) for
  552. * empty collections, and enables clients to determine if such a spliterator
  553. * covers no elements.
  554. *
  555. * @return a {@code Spliterator} over the elements in this collection
  556. * @since 1.8
  557. */
  558. @Override
  559. default Spliterator<E> spliterator() {
  560. return Spliterators.spliterator(this, 0);
  561. }
  562.  
  563. /**
  564. * Returns a sequential {@code Stream} with this collection as its source.
  565. *
  566. * <p>This method should be overridden when the {@link #spliterator()}
  567. * method cannot return a spliterator that is {@code IMMUTABLE},
  568. * {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()}
  569. * for details.)
  570. *
  571. * @implSpec
  572. * The default implementation creates a sequential {@code Stream} from the
  573. * collection's {@code Spliterator}.
  574. *
  575. * @return a sequential {@code Stream} over the elements in this collection
  576. * @since 1.8
  577. */
  578. default Stream<E> stream() {
  579. return StreamSupport.stream(spliterator(), false);
  580. }
  581.  
  582. /**
  583. * Returns a possibly parallel {@code Stream} with this collection as its
  584. * source. It is allowable for this method to return a sequential stream.
  585. *
  586. * <p>This method should be overridden when the {@link #spliterator()}
  587. * method cannot return a spliterator that is {@code IMMUTABLE},
  588. * {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()}
  589. * for details.)
  590. *
  591. * @implSpec
  592. * The default implementation creates a parallel {@code Stream} from the
  593. * collection's {@code Spliterator}.
  594. *
  595. * @return a possibly parallel {@code Stream} over the elements in this
  596. * collection
  597. * @since 1.8
  598. */
  599. default Stream<E> parallelStream() {
  600. return StreamSupport.stream(spliterator(), true);
  601. }
  602. }

  3、实现类UnmodifiableCollection复写了父类的forEach、spliterator方法

    /**
     * @serial include
     */
    static class UnmodifiableCollection<E> implements Collection<E>, Serializable {
        private static final long serialVersionUID = 1820017752578914078L;
        final Collection<? extends E> c;
        UnmodifiableCollection(Collection<? extends E> c) {
            if (c==null)
                throw new NullPointerException();
            this.c = c;
        }
        public int size()                   {return c.size();}
        public boolean isEmpty()            {return c.isEmpty();}
        public boolean contains(Object o)   {return c.contains(o);}
        public Object[] toArray()           {return c.toArray();}
        public <T> T[] toArray(T[] a)       {return c.toArray(a);}
        public String toString()            {return c.toString();}
        public Iterator<E> iterator() {
            return new Iterator<E>() {
                private final Iterator<? extends E> i = c.iterator();
                public boolean hasNext() {return i.hasNext();}
                public E next()          {return i.next();}
                public void remove() {
                    throw new UnsupportedOperationException();
                }
                @Override
                public void forEachRemaining(Consumer<? super E> action) {
                    // Use backing collection version
                    i.forEachRemaining(action);
                }
            };
        }
        public boolean add(E e) {
            throw new UnsupportedOperationException();
        }
        public boolean remove(Object o) {
            throw new UnsupportedOperationException();
        }
        public boolean containsAll(Collection<?> coll) {
            return c.containsAll(coll);
        }
        public boolean addAll(Collection<? extends E> coll) {
            throw new UnsupportedOperationException();
        }
        public boolean removeAll(Collection<?> coll) {
            throw new UnsupportedOperationException();
        }
        public boolean retainAll(Collection<?> coll) {
            throw new UnsupportedOperationException();
        }
        public void clear() {
            throw new UnsupportedOperationException();
        }
        // Override default methods in Collection
        @Override
        public void forEach(Consumer<? super E> action) {
            c.forEach(action);
        }
        @Override
        public boolean removeIf(Predicate<? super E> filter) {
            throw new UnsupportedOperationException();
        }
        @SuppressWarnings("unchecked")
        @Override
        public Spliterator<E> spliterator() {
            return (Spliterator<E>)c.spliterator();
        }
        @SuppressWarnings("unchecked")
        @Override
        public Stream<E> stream() {
            return (Stream<E>)c.stream();
        }
        @SuppressWarnings("unchecked")
        @Override
        public Stream<E> parallelStream() {
            return (Stream<E>)c.parallelStream();
        }
    }

  从上面祖父孙三代可以看到,default就是给接口赋予了原来抽象类的能力,实现类可以像使用抽象类的方法一样,直接使用接口里的方法。

jdk1.8新特性之接口default方法的更多相关文章

  1. JDK1.8新特性(一): 接口的默认方法default

    前言 今天在学习mysql分区优化时,发现一个博客专家大神,对其发布的文章简单学习一下: 一:简介 我们通常所说的接口的作用是用于定义一套标准.约束.规范等,接口中的方法只声明方法的签名,不提供相应的 ...

  2. JDK1.8新特性——Collector接口和Collectors工具类

    JDK1.8新特性——Collector接口和Collectors工具类 摘要:本文主要学习了在Java1.8中新增的Collector接口和Collectors工具类,以及使用它们在处理集合时的改进 ...

  3. java 28 - 7 JDK8的新特性 之 接口可以使用方法

    JDK8的新特性: http://bbs.itcast.cn/thread-24398-1-1.html 其中之一:接口可以使用方法 interface Inter { //抽象方法 public a ...

  4. JDK8新特性之接口默认方法与静态方法

    接口默认方法与静态方法 有这样一些场景,如果一个接口要添加一个方法,那所有的接口实现类都要去实现,而某些实现类根本就不需要实现这个方法也要写一个空实现,所以接口默认方法就是为了解决这个问题. 接口静态 ...

  5. JDK1.8新特性(一) ----Lambda表达式、Stream API、函数式接口、方法引用

    jdk1.8新特性知识点: Lambda表达式 Stream API 函数式接口 方法引用和构造器调用 接口中的默认方法和静态方法 新时间日期API default   Lambda表达式     L ...

  6. jdk1.8新特性之方法引用

    方法引用其实就是方法调用,符号是两个冒号::来表示,左边是对象或类,右边是方法.它其实就是lambda表达式的进一步简化.如果不使用lambda表达式,那么也就没必要用方法引用了.啥是lambda,参 ...

  7. JDK1.8新特性之(三)--函数式接口

    在上一篇文章中我们介绍了JDK1.8的新特性有以下几项. 1.Lambda表达式 2.方法引用 3.函数式接口 4.默认方法 5.Stream 6.Optional类 7.Nashorm javasc ...

  8. JDK1.8新特性之(二)--方法引用

    在上一篇文章中我们介绍了JDK1.8的新特性有以下几项. 1.Lambda表达式 2.方法引用 3.函数式接口 4.默认方法 5.Stream 6.Optional类 7.Nashorm javasc ...

  9. JDK8新特性:接口的静态方法和默认方法

    在jdk8之前,interface之中可以定义变量和方法,变量必须是public.static.final的,方法必须是public.abstract的.由于这些修饰符都是默认的,所以在JDK8之前, ...

随机推荐

  1. js中的数据类型和判断数据类型

    js中的数据类型和判断数据类型 基本数据类型,六大基本数据类型:字符串(String).数字(Number).布尔(Boolean).对象(Object).空(Null).未定义(Undefined) ...

  2. 【转】ubuntu下如何将笔记本自带的键盘关闭

    想必大家都经历过这样的情况:在使用usb接口的外接键盘的时候,很容易按到笔记本自带的键盘,从而导致输入错误.尤其是你将外接键盘放在笔记本键盘上面的时候.怎么解决这个问题呢? 搜索之后,找到了答案.注意 ...

  3. python使用tkinter做界面之颜色

    python使用tkinter做界面之颜色       from tkinter import *colors = '''#FFB6C1 LightPink 浅粉红#FFC0CB Pink 粉红#DC ...

  4. windows下的一些命令

    dir 相当于linux下的ls clear 清屏 netstat 活动连接 | 管道命令 findstr 查询类似linux的grep tasklist 查看进程列表 taskkill 杀死进程 d ...

  5. window环境下创建Flask项目需要安装常见模块命令

    安装Flask环境 pip install flask==0.10.1 使用命令行操作 pip install flask-script 创建表单 pip install flask-wtf 操作数据 ...

  6. MetaPost使用

    简介 MetaPost是一种制图语言,由John D. Hobby开发. 如果你要学习它,可以去下面的网址看看. 官网:http://tug.org/metapost 权威手册:http://tug. ...

  7. [Scala]Scala学习笔记四 类

    1. 简单类与无参方法 class Person { var age = 0 // 必须初始化字段 def getAge() = age // 方法默认为公有的 } 备注 在Scala中,类并不声明为 ...

  8. 《Drools7.0.0.Final规则引擎教程》第4章 4.4 LHS简介&Pattern

    LHS简介 在规则文件组成章节,我们已经了解了LHS的基本使用说明.LHS是规则条件部分的统称,由0个或多个条件元素组成.前面我们已经提到,如果没有条件元素那么默认就是true. 没有条件元素,官方示 ...

  9. Java之引用类型分析(SoftReference/WeakReference/PhantomReference)

    引言: 即使对于Java的很多老鸟来说,如果忽然问他引用的类型,大概率是一脸茫然,不知所措的-.Java中的引用还分类型,神马情况??? 本文将针对这些类型进行分析,帮助您一文知所有类型. Java的 ...

  10. 我也说说Emacs吧(5) - 基本编辑操作

    基本编辑操作 进入编辑模式 标准的emacs用户是遇不到这一节的,因为默认就可以编辑.但是spacemacs用户需要先学习一下强大的vi的模式切换功能了. vi的一个重要特点就是命令特别多,所以一旦学 ...