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

本文详细介绍了Java集合框架的基础知识,包括hashCode()和equals()的实现规则、集合的种类、如何正确使用集合类以及如何进行排序和搜索操作。同时,文章还深入探讨了如何在实际开发中有效地运用这些集合类,旨在帮助开发者更熟练地掌握Java集合框架的使用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[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) == truex.hashCode() ==
y.hashCode()
x.hashCode() ==
y.hashCode()
x.equals(y) == true
x.equals(y) == falseNo 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
HashMapFastest updates (key/values); allows one null key, many
null values.
x

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

NoNo
TreeMapA sorted map.x

SortedBy natural order or
custom comparison rules
LinkedHashMapFaster iterations; iterates by insertion order or last accessed;
allows one null key, many null values.
x

By insertion order
or last access order
No
HashSetFast access, assures no duplicates, provides no ordering.
x
NoNo
TreeSetNo duplicates; iterates in sorted order.
x
SortedBy natural order or
custom comparison rules
LinkedHashSetNo duplicates; iterates by insertion order.
x
By insertion orderNo
ArrayListFast iteration and fast random access.

xBy indexNo
VectorIt's like a slower ArrayList, but it has synchronized methods.

xBy indexNo
LinkedListGood for adding elements to the ends, i.e., stacks and queues.

xBy indexNo
PriorityQueueA to-do list ordered by the elements' priority.


SortedBy 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 MethodsListSetMapDescriptions
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)XGet the location of an object in a List.
Iterator iterator()XXGet an Iterator for a List or a Set.
Set keySet()XReturn a Set containing a Map’s keys.
put(key, value)XAdd 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()XXXReturn the number of elements in a
collection.
Object[] toArray()
T[] toArray(T[])

X

 

XReturn 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 createdMany 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.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值