说明
不讲任何方法,只欣赏艺术
Collection 接口
public interface Collection<E> extends Iterable<E> {
// Query Operations
// 查询操作
int size();
boolean isEmpty();
boolean contains(Object o);
Iterator<E> iterator();
Object[] toArray();
<T> T[] toArray(T[] a);
// Modification Operations
// 修改操作
boolean add(E e);
boolean remove(Object o);
// Bulk Operations
// 批量操作
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c);
boolean removeAll(Collection<?> c);
default boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
boolean removed = false;
final Iterator<E> each = iterator();
while (each.hasNext()) {
if (filter.test(each.next())) {
each.remove();
removed = true;
}
}
return removed;
}
boolean retainAll(Collection<?> c);
void clear();
// Comparison and hashing
// 比较和散列
boolean equals(Object o);
int hashCode();
@Override
default Spliterator<E> spliterator() {
return Spliterators.spliterator(this, 0);
}
default Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
}
default Stream<E> parallelStream() {
return StreamSupport.stream(spliterator(), true);
}
}
List 接口
public interface List<E> extends Collection<E> {
// Query Operations
// 查询操作
int size();
boolean isEmpty();
boolean contains(Object o);
Iterator<E> iterator();
Object[] toArray();
<T> T[] toArray(T[] a);
// Modification Operations
// 修改操作
boolean add(E e);
boolean remove(Object o);
// Bulk Operations
// 批量操作
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c);
boolean removeAll(Collection<?> c);
default boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
boolean removed = false;
final Iterator<E> each = iterator();
while (each.hasNext()) {
if (filter.test(each.next())) {
each.remove();
removed = true;
}
}
return removed;
}
boolean retainAll(Collection<?> c);
void clear();
// Comparison and hashing
// 比较和散列
boolean equals(Object o);
int hashCode();
// Positional Access Operations
E get(int index);
E set(int index, E element);
void add(int index, E element);
E remove(int index);
// Search Operations
int indexOf(Object o);
int lastIndexOf(Object o);
// List Iterators
ListIterator<E> listIterator();
ListIterator<E> listIterator(int index);
// View
List<E> subList(int fromIndex, int toIndex);
}
Set 接口和 Collection 几乎一样
在 collection 基础上增加了 根据位置操作的方法。
可不是将 add 放一起,remove 放一起。
jdk 设计的时候很讲究艺术,我们是否也应该像他们一样,而不仅仅是写个注释注解,应该将同类型的归类。
就比如写 mapper 接口的时候,我们是否一股脑的增删改查,当之后有新功能的时候统一往后排,还是所有add 放一起,remove 放一起。
是否有个模板,在写接口的时候先这么规定下:
public class XXX {
// Query Operations
// Modification Operations
// Bulk Operations
// Comparison and hashing
}
可以有效增加合作效率并降低维护成本呢