`

Java基础恶补——泛型和集合

    博客分类:
  • Java
 
阅读更多

[SCJP Sun Certified Programmer for Java 6 Study Guide (Exam 310-065)]  chapter7

 

一. Overriding hashCode() and equals()

1. equals(), hashCode(), and toString() are public.

2. Override toString() so that System.out.println() or other methods can see something useful, like your object's state.

3. 用 == 判断2个引用变量是否指向同1个对象;用 equals() 判断2个对象是否意义上相等。

4. If you don't override equals(), your objects won't be useful hashing keys.

5. If you don't override equals(), different objects can't be considered equal.

6. Strings and wrappers override equals() and make good hashing keys.

7. overriding equals() 时, 首先使用 instanceof 判断待比较对象的类型是否正确。

8. overriding equals() 时,比较对象的关键属性。

9. equals() 的规则:

1) 自反性: x.equals(x)==true

2) 对称性: 如果x.equals(y)==true, 则y.equals(x)==true

3) 传递性: 如果x.equals(y)==true, y.equals(z)==true 则x.equals(z)==true

4) 一致性: 任何时候调用 x.equals(y) ,其结果始终不变

5) 非空性: 对非空的引用变量x, x.equals(null)==false

10. 如果 x.equals(y)==true, 则 x.hashCode() == y.hashCode() == true.

11. If you override equals(), override hashCode().

12. HashMap, HashSet, Hashtable, LinkedHashMap, & LinkedHashSet use hashing.

13. An appropriate hashCode() override sticks to the hashCode() contract.

14. An efficient hashCode() override distributes keys evenly across its buckets.

15. An overridden equals() must be at least as precise as its hashCode() mate.

16. 如果2个对象 equal,则它们的 hashcodes 必须也 equal.

17. 所有实例对象的 hashCode() 返回相同的值是合法的(虽然这是非常低效的实践)。

18. hashCode() 的规则:

1) 一致性: 任何时候调用 hashCode() ,始终得到相同的integer值。

2) 如果2个对象通过equals() 被判定为是相同的,则调用其各自的 hashCode() 方法也应得到相同的integer值。

3) 如果2个对象通过equals() 被判定为非相同的,则调用其各自的 hashCode() 方法允许得到相同的integer值。

19. transient variables aren't appropriate for equals() and hashCode().

20. hashCode() 与 equals() 关系:

Condition Required Not Required (But Allowed)
x.equals(y) == true x.hashCode() ==
y.hashCode()
x.hashCode() ==
y.hashCode()
x.equals(y) == true
x.equals(y) == false No hashCode()
requirements
x.hashCode() !=
y.hashCode()
x.equals(y) == false

 

二. 集合

1. Common collection activities include adding objects, removing objects, verifying object inclusion, retrieving objects, and iterating.

2. Three meanings for "collection":

1) collection Represents the data structure in which objects are stored

2) Collection java.util interface from which Set and List extend

3) Collections A class that holds static collection utility methods

3. Four basic flavors of collections include Lists, Sets, Maps, Queues:

1) Lists of things Ordered, duplicates allowed, with an index.

2) Sets of things May or may not be ordered and/or sorted; duplicates not allowed.

3) Maps of things with keys May or may not be ordered and/or sorted;
duplicate keys are not allowed.

4) Queues of things to process Ordered by FIFO or by priority.

4. Four basic sub-flavors of collections Sorted, Unsorted, Ordered, Unordered.

1) Ordered Iterating through a collection in a specific, non-random order.

2) Sorted Iterating through a collection in a sorted order.

5. Sorting can be alphabetic, numeric, or programmer-defined.

6. 常用集合类:

Class Map Set List Ordered Sorted
HashMap Fastest updates (key/values); allows one null key, many
null values.
x

No No
Hashtable Like a slower HashMap (as with Vector, due to its synchronized
methods). No null values or null keys allowed.
x

No No
TreeMap A sorted map. x

Sorted By natural order or
custom comparison rules
LinkedHashMap Faster iterations; iterates by insertion order or last accessed;
allows one null key, many null values.
x

By insertion order
or last access order
No
HashSet Fast access, assures no duplicates, provides no ordering.
x
No No
TreeSet No duplicates; iterates in sorted order.
x
Sorted By natural order or
custom comparison rules
LinkedHashSet No duplicates; iterates by insertion order.
x
By insertion order No
ArrayList Fast iteration and fast random access.

x By index No
Vector It's like a slower ArrayList, but it has synchronized methods.

x By index No
LinkedList Good for adding elements to the ends, i.e., stacks and queues.

x By index No
PriorityQueue A to-do list ordered by the elements' priority.


Sorted By to-do order

 

三. 使用集合类

1. 集合类仅能存储Objects,但原子类型可以被autoboxed.

2. Iterate with the enhanced for, or with an Iterator via hasNext() & next().

3. hasNext() determines if more elements exist; the Iterator does NOT move.

4. next() returns the next element AND moves the Iterator forward.

5. To work correctly, a Map's keys must override equals() and hashCode().

6. Queues 用 offer() 增加元素, poll() 删除队首元素, peek() to look at the head of a queue.

7. As of Java 6 TreeSets and TreeMaps have new navigation methods like floor() and higher().

8. You can create/extend "backed" sub-copies of TreeSets and TreeMaps.

9. Important "Navigation" Related Methods:

Method Description
TreeSet.ceiling(e) Returns the lowest element >= e
TreeMap.ceilingKey(key) Returns the lowest key >= key
TreeSet.higher(e) Returns the lowest element > e
TreeMap.higherKey(key) Returns the lowest key > key
TreeSet.floor(e) Returns the highest element <= e
TreeMap.floorKey(key) Returns the highest key <= key
TreeSet.lower(e) Returns the highest element < e
TreeMap.lowerKey(key) Returns the highest key < key
TreeSet.pollFirst() Returns and removes the first entry
TreeMap.pollFirstEntry() Returns and removes the first key-value pair
TreeSet.pollLast() Returns and removes the last entry
TreeMap.pollLastEntry() Returns and removes the last key-value pair
TreeSet.descendingSet() Returns a NavigableSet in reverse order
TreeMap.descendingMap() Returns a NavigableMap in reverse order

 

10. Important "Backed Collection" Methods for TreeSet and TreeMap:

Method Description
headSet(e, b*) Returns a subset ending at element e and exclusive of e
headMap(k, b*) Returns a submap ending at key k and exclusive of key k
tailSet(e, b*) Returns a subset starting at and inclusive of element e
tailMap(k, b*) Returns a submap starting at and inclusive of key k
subSet(s, b*, e, b*) Returns a subset starting at element s and ending just before element e
subMap(s, b*, e, b*) Returns a submap starting at key s and ending just before key e

 

11. Key Methods in List, Set, and Map:

Key Interface Methods List Set Map Descriptions
boolean add(element)
boolean add(index, element)
X
X

X

 

Add an element. For Lists, optionally
add the element at an index point.
boolean contains(object)
boolean containsKey(object key)
boolean containsValue(object value)

X

 

 

X

 

X
X

Search a collection for an object (or,
optionally for Maps a key), return the
result as a boolean.
object get(index)
object get(key)

X

 

 

X

Get an object from a collection, via an
index or a key.
int indexOf(object) X Get the location of an object in a List.
Iterator iterator() X X Get an Iterator for a List or a Set.
Set keySet() X Return a Set containing a Map’s keys.
put(key, value) X Add a key/value pair to a Map.
remove(index)
remove(object)
remove(key)

X
X

 

X

 

 

X

Remove an element via an index, or
via the element’s value, or via a key.
int size() X X X Return the number of elements in a
collection.
Object[] toArray()
T[] toArray(T[])

X

 

X Return an array containing the
elements of the collection.

 

 

四. Sorting and Searching Arrays and Lists

1. Sorting can be in natural order, or via a Comparable or many Comparators.

2. Implement Comparable using compareTo(); provides only one sort order.

3. Create many Comparators to sort a class many ways; implement compare().

4. To be sorted and searched, a List's elements must be comparable.

5. To be searched, an array or List must first be sorted.

6. Comparable Comparator 对比:

java.lang.Comparable java.util.Comparator
int objOne.compareTo(objTwo) int compare(objOne, objTwo)
Returns
negative if objOne < objTwo
zero if objOne == objTwo
positive if objOne > objTwo
Same as Comparable
You must modify the class whose
instances you want to sort.
You build a class separate from the class whose instances you
want to sort.
Only one sort sequence can be created Many sort sequences can be created
Implemented frequently in the API by:
String, Wrapper classes, Date, Calendar...
Meant to be implemented to sort instances of third-party
classes.

 

五. 工具类: Collections and Arrays

1. Both of these java.util classes provide

1) A sort() method. Sort using a Comparator or sort using natural order.

2) A binarySearch() method. Search a pre-sorted array or List.

2. Arrays.asList() creates a List from an array and links them together.

3. Collections.reverse() reverses the order of elements in a List.

4. Collections.reverseOrder() returns a Comparator that sorts in reverse.

5. Lists and Sets have a toArray() method to create arrays.

6. Key Methods in Arrays and Collections:

Key Methods in java.util.Arrays Description
static List asList(T[]) Convert an array to a List (and bind them).
static int binarySearch(Object[], key)
static int binarySearch(primitive[], key)
Search a sorted array for a given value, return
an index or insertion point.
static int binarySearch(T[], key, Comparator) Search a Comparator-sorted array for a value.
static boolean equals(Object[], Object[])
static boolean equals(primitive[], primitive[])
Compare two arrays to determine if their
contents are equal.
public static void sort(Object[ ] )
public static void sort(primitive[ ] )
Sort the elements of an array by natural
order.
public static void sort(T[], Comparator) Sort the elements of an array using a
Comparator.
public static String toString(Object[])
public static String toString(primitive[])
Create a String containing the contents of
an array.
Key Methods in java.util.Collections Descriptions
Key Methods in java.util.Collections Descriptions
static int binarySearch(List, key)
static int binarySearch(List, key, Comparator)
Search a "sorted" List for a given value,
return an index or insertion point.
static void reverse(List) Reverse the order of elements in a List.
static Comparator reverseOrder()
static Comparator reverseOrder(Comparator)
Return a Comparator that sorts the reverse of
the collection’s current sort sequence.
static void sort(List)
static void sort(List, Comparator)
Sort a List either by natural order or by a
Comparator.

 

六. 泛型

1. Generics let you enforce compile-time type safety on Collections (or other classes and methods declared using generic type parameters).

2. An ArrayList<Animal> can accept references of type Dog, Cat, or any other subtype of Animal (subclass, or if Animal is an interface, implementation).

3. When using generic collections, a cast is not needed to get (declared type) elements out of the collection. With non-generic collections, a cast is required.

4. You can pass a generic collection into a method that takes a non-generic collection, but the results may be disastrous. The compiler can't stop the method from inserting the wrong type into the previously type safe collection.

5. If the compiler can recognize that non-type-safe code is potentially endangering something you originally declared as type-safe, you will get a compiler warning.

6. "Compiles without error" is not the same as "compiles without warnings." A compilation warning is not considered a compilation error or failure.

7. Generic type information does not exist at runtime—it is for compile-time safety only. Mixing generics with legacy code can create compiled code that may throw an exception at runtime.

8. Polymorphic assignments applies only to the base type, not the generic type parameter.

You can say
List<Animal> aList = new ArrayList<Animal>(); // yes
You can't say
List<Animal> aList = new ArrayList<Dog>(); // no

9. The polymorphic assignment rule applies everywhere an assignment can be made.

10. Wildcard syntax allows a generic method, accept subtypes (or supertypes) of the declared type of the method argument.

11. The wildcard keyword extends is used to mean either "extends" or "implements." So in <? extends Dog>, Dog can be a class or an interface.

12. When using a wildcard, List<? extends Dog>, the collection can be accessed but not modified.

13. When using a wildcard, List<?>, any generic type can be assigned to the reference, but for access only, no modifications.

14. List<Object> refers only to a List<Object>, while List<?> or List<? extends Object> can hold any type of object, but for access only.

15. Declaration conventions for generics use T for type and E for element:

public interface List<E> // API declaration for List
boolean add(E o) // List.add() declaration

16. The generics type identifier can be used in class, method, and variable declarations.

17. You can use more than one parameterized type in a declaration

18. You can declare a generic method using a type not defined in the class.

public <T> void makeList(T t) { }
is NOT using T as the return type. This method has a void return type, but
to use T within the method's argument you must declare the <T>, which
happens before the return type.

 

分享到:
评论

相关推荐

    博客《夯实JAVA基本之一——泛型详解(1)》对应源码

    在《夯实JAVA基本之一——泛型详解(1)》的博客中,作者深入浅出地探讨了泛型的基本概念和用法,本文将基于这个博客源码,详细解析泛型的相关知识点。 首先,泛型的主要目标是提高代码的类型安全性。在未引入泛型...

    博客《夯实JAVA基本之一——泛型详解(2)》对应源码

    在《夯实JAVA基本之一——泛型详解(2)》这篇博客中,作者深入探讨了泛型的高级用法和概念,这些内容对于理解和掌握Java泛型至关重要。 首先,泛型的基本语法是以尖括号 `&lt;T&gt;` 表示,其中 `T` 是一个类型参数,代表...

    net基础——泛型PPT教案学习.pptx

    net基础——泛型PPT教案学习.pptx

    Java集合框架及泛型

    在实际开发中,理解和熟练运用Java集合框架和泛型能够大大提高代码的可维护性和安全性,减少类型转换的麻烦,并使得代码更易于理解和复用。通过以上讲解,相信你已经对这两个主题有了更深入的理解。通过练习和应用,...

    [Java泛型和集合].(Java.Generics.and.Collections).文字版

    Java泛型和集合是Java编程语言中的核心特性,它们极大地提高了代码的类型安全性和可读性,同时也简化了集合操作。本资料 "[Java泛型和集合].(Java.Generics.and.Collections).Maurice.Naftalin&amp;Philip.Wadler....

    [Java泛型和集合].

    Java泛型和集合是Java编程语言中的核心特性,它们极大地提高了代码的类型安全性和可读性,同时也简化了集合操作。本资料主要基于Maurice Naftalin和Philip Wadler合著的《Java泛型和集合》进行讨论。 首先,我们要...

    java泛型集合 java集合 集合 java Collection

    总的来说,Java泛型集合和集合框架提供了强大的数据存储和处理能力,而`Collection`接口作为基础,连接了各种集合类型。了解并熟练掌握这些概念和用法,对于提高Java编程效率和代码质量至关重要。

    C 设计新思维——泛型编程与设计范式之应用 PDF.rar

    C 设计新思维——泛型编程与设计范式之应用 PDF,候捷译序。㆒般人对C templates 的粗略印象,大约停留在「容器(containers)」的制作上。稍有研究由会发现,templates衍生出来的C Generic Programming(泛型编程)技术...

    学士后Java集合框架和泛型课后习题答案

    通过学习和练习这些内容,你可以深入理解Java集合框架的核心概念和泛型的应用,从而在编程实践中更加灵活和高效地处理数据。同时,不断的学习和实践是提升技能的关键,希望你能在Java世界中不断进步。

    Java泛型和集合-英文版

    根据提供的文件信息,我们可以确定本书的标题为《Java泛型和集合》(Java Generics and Collections),作者为Maurice Naftalin和Philip Wadler。...本书适合有一定Java基础并希望深入了解泛型和集合框架的读者。

    java基础——————试题库

    这份“java基础——————试题库”资源旨在帮助学习者系统地复习和深入理解Java的基础知识,确保他们能够全方位地掌握这一强大的编程工具。下面将详细阐述Java的基础知识点。 1. **Java简介** - Java是由Sun ...

    Java基础笔记之集合框架和泛型

    详细的介绍了集合框架的用法,及其语法规则,剖析了使用的使用注意事项,帮助更牢靠的掌握集合框架的知识及泛型内容。谢谢

    C#泛型集合与非泛型集合

    根据是否支持泛型特性,这些集合大致可以分为两类:泛型集合和非泛型集合。本文将详细探讨这两类集合的特点、优缺点,并通过具体示例来说明为什么在C# 2.0及以上版本中,推荐使用泛型集合。 #### 二、非泛型集合...

    Java如何获取泛型类型

    Java 运行时如何获取泛型参数的类型 Java类型Type 之 ParameterizedType,GenericArrayType,TypeVariabl,WildcardType 从实现的接口获取泛型参数 定义一个泛型父类: public interface SuperClass { String ...

Global site tag (gtag.js) - Google Analytics