存储对象可以使用数组 (基本数据类型 & 引用数据类型) 和集合 (引用数据类型),用数组存储对象的弊端有:一旦创建,其长度不可变;数组中真正存储的对象个数不可知,除非自定义类。使用集合可以解决这些问题。
JDK提供的集合API位于java.util包内。Java 集合可分为 Collection 和 Map 两种体系。
对象排序接口:
容器工具类:
在 Java5 之前,Java 集合会丢失容器中所有对象的数据类型,把所有对象都当成 Object 类型处理;从 Java5 增加了泛型以后,Java 集合可以记住容器中对象的数据类型。
方法摘要 | |
---|---|
boolean | add(E e) 确保此 collection 包含指定的元素(可选操作)。 |
boolean | addAll(Collection<? extends E> c) 将指定 collection 中的所有元素都添加到此 collection 中(可选操作)。 |
void | clear() 移除此 collection 中的所有元素(可选操作)。 |
boolean | contains(Object o) 如果此 collection 包含指定的元素,则返回 true。 |
boolean | containsAll(Collection<?> c) 如果此 collection 包含指定 collection 中的所有元素,则返回 true。 |
boolean | equals(Object o) 比较此 collection 与指定对象是否相等。 |
int | hashCode() 返回此 collection 的哈希码值。 |
boolean | isEmpty() 如果此 collection 不包含元素,则返回 true。 |
Iterator<E> | iterator() 返回在此 collection 的元素上进行迭代的迭代器。 |
boolean | remove(Object o) 从此 collection 中移除指定元素的单个实例,如果存在的话(可选操作)。 |
boolean | removeAll(Collection<?> c) 移除此 collection 中那些也包含在指定 collection 中的所有元素(可选操作)。 |
boolean | retainAll(Collection<?> c) 仅保留此 collection 中那些也包含在指定 collection 的元素(可选操作)。 |
int | size() 返回此 collection 中的元素数。 |
Object[] | toArray() 返回包含此 collection 中所有元素的数组。 |
<T> T[] | toArray(T[] a) 返回包含此 collection 中所有元素的数组;返回数组的运行时类型与指定数组的运行时类型相同。 |
增(add, addAll)、删(clear, remove, removeAll),size,contains、containsAll,equals,isEmpty
List集合类中元素有序、且可重复,集合中的每个元素都有其对应的顺序索引。
要求List集合中的元素重写equals方法,才能适当地进行操作(如remove(Object obj)等)。
List 集合里添加了一些根据索引来操作集合元素的方法:
JDK API中List接口的实现类常用的有:ArrayList、LinkedList和Vector。
ArrayList 是线程不安全的,而 Vector 是线程安全的,即使为保证 List 集合线程安全,也不推荐使用Vector。
Arrays.asList(…) 方法返回的 List 集合既不是 ArrayList 实例,也不是 Vector 实例。 Arrays.asList(…) 返回值是一个固定长度的 List 集合。
Modifier and Type | Method and Description |
---|---|
boolean | add(E e) Appends the specified element to the end of this list. |
void | add(int index, E element) Inserts the specified element at the specified position in this list. |
boolean | addAll(Collection<? extends E> c) Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s Iterator. |
boolean | addAll(int index, Collection<? extends E> c) Inserts all of the elements in the specified collection into this list, starting at the specified position. |
void | clear() Removes all of the elements from this list. |
Object | clone() Returns a shallow copy of this ArrayList instance. |
boolean | contains(Object o) Returns true if this list contains the specified element. |
void | ensureCapacity(int minCapacity) Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument. |
E | get(int index) Returns the element at the specified position in this list. |
int | indexOf(Object o) Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. |
boolean | isEmpty() Returns true if this list contains no elements. |
Iterator<E> | iterator() Returns an iterator over the elements in this list in proper sequence. |
int | lastIndexOf(Object o) Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. |
ListIterator<E> | listIterator() Returns a list iterator over the elements in this list (in proper sequence). |
ListIterator<E> | listIterator(int index) Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list. |
E | remove(int index) Removes the element at the specified position in this list. |
boolean | remove(Object o) Removes the first occurrence of the specified element from this list, if it is present. |
boolean | removeAll(Collection<?> c) Removes from this list all of its elements that are contained in the specified collection. |
protected void | removeRange(int fromIndex, int toIndex) Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive. |
boolean | retainAll(Collection<?> c) Retains only the elements in this list that are contained in the specified collection. |
E | set(int index, E element) Replaces the element at the specified position in this list with the specified element. |
int | size() Returns the number of elements in this list. |
List<E> | subList(int fromIndex, int toIndex) Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. |
Object[] | toArray() Returns an array containing all of the elements in this list in proper sequence (from first to last element). |
<T> T[] | toArray(T[] a) Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. |
void | trimToSize() Trims the capacity of this ArrayList instance to be the list’s current size. |
对于频繁的插入或删除元素的操作,建议使用LinkedList类,效率较高。
新增方法:
Vector 是一个古老的集合,JDK1.0就有了。大多数操作与ArrayList相同,区别之处在于Vector是线程安全的。
新增方法:
在各种list中,最好把ArrayList作为缺省选择。当插入、删除频繁时,使用LinkedList;Vector总是比ArrayList慢,所以尽量避免使用。
List 额外提供了一个 listIterator() 方法,该方法返回一个 ListIterator 对象, ListIterator 接口继承了 Iterator 接口,提供了专门操作 List 的方法:
Iterator和ListIterator主要异同点:
总结:
即两者都有查、删;ListIterator多了增、改,加强了查。
HashSet 按 Hash 算法来存储集合中的元素,因此具有很好的存取和查找性能。
当向 HashSet 集合中存入一个元素时,HashSet 会调用该对象的 hashCode() 方法来得到该对象的 hashCode 值,然后根据 hashCode 值决定该对象在 HashSet 中的存储位置。
HashSet 集合判断两个元素相等的标准:两个对象通过 hashCode() 方法比较相等,并且两个对象的 equals() 方法返回值也相等。重写hashCode()的原则是要尽量保证与equals()一致,即hashCode不同的两个对象,应不相等,hashCode相同,应相等。
LinkedHashSet 是 HashSet 的子类,也是根据元素的 hashCode 值来决定元素的存储位置,但它同时使用链表维护元素的次序,这使得元素看起来是以插入顺序保存的。
LinkedHashSet插入性能略低于 HashSet(因为需要维护链表),但在迭代访问 Set 里的全部元素时有很好的性能。
TreeSet 是 SortedSet 接口的实现类,TreeSet 可以确保集合元素处于排序状态。
向TreeSet中添加的必须是同一个类的对象,并且这个类必须实现Comparable接口并实现compareTo(Object obj)方法(或使用Comparator),TreeSet中的两个对象通过该方法的返回值来比较大小。设计时应使hashCode、equals、compareTo或compare保持一致。
当向TreeSet中添加自定义类的对象时,有两种排序方法:①自然排序②定制排序
TreeSet 会调用集合元素的 compareTo(Object obj) 方法来比较元素之间的大小关系,然后将集合元素按升序排列。
public class Person implements Comparable {
private String name;
private Integer age;
...
@Override
public int compareTo(Object obj) {
if (obj instanceof Person) {
Person person = (Person) obj;
int i = this.age.compareTo(person.getAge());
if(i == 0) {
return this.name.compareTo(person.getName());
}
return i;
}
return 0;
}
}
实现Comparator中的int compare(T o1,T o2)方法,比较o1和o2的大小:如果方法返回正整数,则表示o1大于o2;如果返回0,表示相等;返回负整数,表示o1小于o2。
将实现了Comparator接口的对象作为形参传递给TreeSet的构造器。
// 1.创建一个实现了Comparator接口的类对象
Comparator comparator = new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof Customer && o2 instanceof Customer) {
Customer c1 = (Customer) o1;
Customer c2 = (Customer) o2;
int i = c1.getId().compareTo(c2.getId());
if(i == 0) {
return c1.getName().compareTo(c2.getName());
}
return i;
}
return 0;
}
};
// 2.将此对象作为形参传递给TreeSet的构造器
TreeSet set = new TreeSet(comparator);
...
Map与Collection并列存在。用于保存具有映射关系的数据: Key-Value。
Map 中的 key 和 value 可以是任何引用类型的数据。
Map 中的 key 用 Set 存放,对key的类的要求与Set中元素类似。
常用String类作为Map的“键”。
当后添加的元素的key值与已有的key重复时,后来的数据会覆盖原有的数据。
Modifier and Type | Method and Description |
---|---|
void | clear() Removes all of the mappings from this map (optional operation). |
boolean | containsKey(Object key) Returns true if this map contains a mapping for the specified key. |
boolean | containsValue(Object value) Returns true if this map maps one or more keys to the specified value. |
Set<Map.Entry<K,V>> | entrySet() Returns a Setview of the mappings contained in this map. |
boolean | equals(Object o) Compares the specified object with this map for equality. |
V | get(Object key) Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. |
int | hashCode() Returns the hash code value for this map. |
boolean | isEmpty() Returns true if this map contains no key-value mappings. |
Set<K> | keySet() Returns a Set view of the keys contained in this map. |
V | put(K key, V value) Associates the specified value with the specified key in this map (optional operation). |
void | putAll(Map<? extends K,? extends V> m) Copies all of the mappings from the specified map to this map (optional operation). |
V | remove(Object key) Removes the mapping for a key from this map if it is present (optional operation). |
int | size() Returns the number of key-value mappings in this map. |
Collection<V> | values() Returns a Collectionview of the values contained in this map. |
HashMap 判断两个 key 相等的标准是:两个 key 通过 equals() 方法返回 true,hashCode 值也相等。 HashMap 判断两个 value相等的标准是:两个 value 通过 equals() 方法返回 true。
Map map = new HashMap();
map.put("AA", 213);
map.put("AB", 213);
map.put("BB", 456);
map.put(123, "CC");
map.put(null, null);
map.put(new Person("DD", 12), null);
// 遍历key集
Set set = map.keySet();
for(Object obj : set) {
System.out.println(obj);
}
// 遍历value
Collection values = map.values();
for(Object obj : values) {
System.out.println(obj);
}
// 遍历key-value
// 方式一
for(Object obj : set) {
System.out.println(obj + ": " + map.get(obj));
}
// 方式二
Set entrySet = map.entrySet();
for(Object obj : entrySet) {
Map.Entry entry = (Entry) obj;
System.out.println(entry);
}
与LinkedHashSet类似,使用链表维护添加进Map中的顺序,遍历Map时是按添加的顺序遍历的。
对key进行排序,对key的要求可参考TreeSet。
古老的 Map 实现类,线程安全,不允许使用 null 作为 key 和 value。不建议使用。
Hashtable 的子类,用于处理属性文件。
由于属性文件里的 key、value 都是字符串类型,所以 Properties 里的 key 和 value 都是字符串类型。
Properties properties = new Properties();
properties.load(new FileInputStream(new File("test.properties")));
System.out.println(properties.getProperty("user"));
Collections 是一个操作 Set、List 和 Map 等集合的工具类。
Collections 中提供了一系列静态的方法对集合元素进行排序、查询和修改等操作,还提供了对集合对象设置不可变、对集合对象实现同步控制等方法。
Modifier and Type | Method and Description |
---|---|
static <T> boolean | addAll(Collection<? super T> c, T... elements) Adds all of the specified elements to the specified collection. |
static <T> Queue<T> | asLifoQueue(Deque<T> deque) Returns a view of a Deque as a Last-in-first-out (Lifo) Queue. |
static <T> int | binarySearch(List<? extends Comparable<? super T>> list, T key) Searches the specified list for the specified object using the binary search algorithm. |
static <T> int | binarySearch(List<? extends T> list, T key, Comparator<? super T> c) Searches the specified list for the specified object using the binary search algorithm. |
static <E> Collection<E> | checkedCollection(Collection<E> c, Class<E> type) Returns a dynamically typesafe view of the specified collection. |
static <E> List<E> | checkedList(List<E> list, Class<E> type) Returns a dynamically typesafe view of the specified list. |
static <K,V> Map<K,V> | checkedMap(Map<K,V> m, Class<K> keyType, Class<V> valueType) Returns a dynamically typesafe view of the specified map. |
static <E> Set<E> | checkedSet(Set<E> s, Class<E> type) Returns a dynamically typesafe view of the specified set. |
static <K,V> SortedMap<K,V> | checkedSortedMap(SortedMap<K,V> m, Class<K> keyType, Class<V> valueType) Returns a dynamically typesafe view of the specified sorted map. |
static <E> SortedSet<E> | checkedSortedSet(SortedSet<E> s, Class<E> type) Returns a dynamically typesafe view of the specified sorted set. |
static <T> void | copy(List<? super T> dest, List<? extends T> src) Copies all of the elements from one list into another. |
static boolean | disjoint(Collection<?> c1, Collection<?> c2) Returns true if the two specified collections have no elements in common. |
static <T> Enumeration<T> | emptyEnumeration() Returns an enumeration that has no elements. |
static <T> Iterator<T> | emptyIterator() Returns an iterator that has no elements. |
static <T> List<T> | emptyList() Returns the empty list (immutable). |
static <T> ListIterator<T> | emptyListIterator() Returns a list iterator that has no elements. |
static <K,V> Map<K,V> | emptyMap() Returns the empty map (immutable). |
static <T> Set<T> | emptySet() Returns the empty set (immutable). |
static <T> Enumeration<T> | enumeration(Collection<T> c) Returns an enumeration over the specified collection. |
static <T> void | fill(List<? super T> list, T obj) Replaces all of the elements of the specified list with the specified element. |
static int | frequency(Collection<?> c, Object o) Returns the number of elements in the specified collection equal to the specified object. |
static int | indexOfSubList(List<?> source, List<?> target) Returns the starting position of the first occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence. |
static int | lastIndexOfSubList(List<?> source, List<?> target) Returns the starting position of the last occurrence of the specified target list within the specified source list, or -1 if there is no such occurrence. |
static <T> ArrayList<T> | list(Enumeration<T> e) Returns an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration. |
static <T extends Object & Comparable<? super T>> T | max(Collection<? extends T> coll) Returns the maximum element of the given collection, according to the natural ordering of its elements. |
static <T> T | max(Collection<? extends T> coll, Comparator<? super T> comp) Returns the maximum element of the given collection, according to the order induced by the specified comparator. |
static <T extends Object & Comparable<? super T>> T | min(Collection<? extends T> coll) Returns the minimum element of the given collection, according to the natural ordering of its elements. |
static <T> T | min(Collection<? extends T> coll, Comparator<? super T> comp) Returns the minimum element of the given collection, according to the order induced by the specified comparator. |
static <T> List<T> | nCopies(int n, T o) Returns an immutable list consisting of n copies of the specified object. |
static <E> Set<E> | newSetFromMap(Map<E,Boolean> map) Returns a set backed by the specified map. |
static <T> boolean | replaceAll(List<T> list, T oldVal, T newVal) Replaces all occurrences of one specified value in a list with another. |
static void | reverse(List<?> list) Reverses the order of the elements in the specified list. |
static <T> Comparator<T> | reverseOrder() Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface. |
static <T> Comparator<T> | reverseOrder(Comparator<T> cmp) Returns a comparator that imposes the reverse ordering of the specified comparator. |
static void | rotate(List<?> list, int distance) Rotates the elements in the specified list by the specified distance. |
static void | shuffle(List<?> list) Randomly permutes the specified list using a default source of randomness. |
static void | shuffle(List<?> list, Random rnd) Randomly permute the specified list using the specified source of randomness. |
static <T> Set<T> | singleton(T o) Returns an immutable set containing only the specified object. |
static <T> List<T> | singletonList(T o) Returns an immutable list containing only the specified object. |
static <K,V> Map<K,V> | singletonMap(K key, V value) Returns an immutable map, mapping only the specified key to the specified value. |
static <T extends Comparable<? super T>> void | sort(List<T> list) Sorts the specified list into ascending order, according to the natural ordering of its elements. |
static <T> void | sort(List<T> list, Comparator<? super T> c) Sorts the specified list according to the order induced by the specified comparator. |
static void | swap(List<?> list, int i, int j) Swaps the elements at the specified positions in the specified list. |
static <T> Collection<T> | synchronizedCollection(Collection<T> c) Returns a synchronized (thread-safe) collection backed by the specified collection. |
static <T> List<T> | synchronizedList(List<T> list) Returns a synchronized (thread-safe) list backed by the specified list. |
static <K,V> Map<K,V> | synchronizedMap(Map<K,V> m) Returns a synchronized (thread-safe) map backed by the specified map. |
static <T> Set<T> | synchronizedSet(Set<T> s) Returns a synchronized (thread-safe) set backed by the specified set. |
static <K,V> SortedMap<K,V> | synchronizedSortedMap(SortedMap<K,V> m) Returns a synchronized (thread-safe) sorted map backed by the specified sorted map. |
static <T> SortedSet<T> | synchronizedSortedSet(SortedSet<T> s) Returns a synchronized (thread-safe) sorted set backed by the specified sorted set. |
static <T> Collection<T> | unmodifiableCollection(Collection<? extends T> c) Returns an unmodifiable view of the specified collection. |
static <T> List<T> | unmodifiableList(List<? extends T> list) Returns an unmodifiable view of the specified list. |
static <K,V> Map<K,V> | unmodifiableMap(Map<? extends K,? extends V> m) Returns an unmodifiable view of the specified map. |
static <T> Set<T> | unmodifiableSet(Set<? extends T> s) Returns an unmodifiable view of the specified set. |
static <K,V> SortedMap<K,V> | unmodifiableSortedMap(SortedMap<K,? extends V> m) Returns an unmodifiable view of the specified sorted map. |
static <T> SortedSet<T> | unmodifiableSortedSet(SortedSet<T> s) Returns an unmodifiable view of the specified sorted set. |
Collection可用Iterator遍历,List首选ArrayList,Set首选HashSet,Map首选HashMap。
List元素类该重写equals,Set元素类和Map的key所在类该重写equals和hashCode,TreeSet和TreeMap涉及到排序,所以还得有比较的操作。
此外,为解决元素存储的安全性问题,和读取数据时需要类型强转的问题,使代码更加健壮和简介,常使用泛型。
注:以上笔记参考自尚硅谷
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有