java编程思想读书笔记--使用C o l l e c t i o n s

本文介绍了如何使用Java中的Collections框架进行集合操作,包括添加、删除、查询等常见操作,并提供了示例代码。
使用C o l l e c t i o n s
下面这张表格总结了用一个集合能做的所有事情(亦可对Set 和List 做同样的事情,尽管List 还提供了一
些额外的功能)。Map 不是从Collection 继承的,所以要单独对待。
B o o l e a n a d d ( O b j e c t ) *Ensures that the Collection contains the argument. Returns false if
it doesn ’t add th e argument.
B o o l e a n
a d d A l l ( C o l l e c t i o n )
*Adds all the elements in the argument. Returns true if any elements
were added.
v o i d c l e a r ( ) *Removes all the elements in the Collection.
Boolean contains(Object) True if the Collection contains the argument.
B o o l e a n True if the Collection contains all the elements in the argument.
236
containsAll(Collection)
B o o l e a n i s E m p t y ( ) True if the Collection has no elements.
I t e r a t o r i t e r a t o r ( ) Returns an Iterator that you can use to move through the elements in
the Collection.
Boolean remove(Object) *If the argument is in the Collection, one instance of that element
is removed. Returns true if a removal occurred.
B o o l e a n
r e m o v e A l l ( C o l l e c t i o n )
*Removes all the elements that are contained in the argument.
Returns true if any removals occurred.
B o o l e a n
r e t a i n A l l ( C o l l e c t i o n )
*Retains only elements that are contained in the argument (an
“intersection” from set theory). Returns true if any changes
occurred.
i n t s i z e ( ) Returns the number of elements in the Collection.
O b j e c t [ ] t o A r r a y ( ) Returns an array containing all the elements in the Collection.
O b j e c t [ ]
t o A r r a y ( O b j e c t [ ] a )
Returns an array containing all the elements in the Collection,
whose type is that of the array a rather than plain O b j e c t (you must
cast the array to the right type).
*This is an “optional ” method, which means it might not be
implemented by a particular Collection. If not, that method throws
an U n s u p p o r t e d O p e r a t i o n E x c e p t i o n . Exceptions will be covered in
Chapter 9.
boolean add(Object) *保证集合内包含了自变量。如果它没有添加自变量,就返回false(假)
boolean addAll(Collection) *添加自变量内的所有元素。如果没有添加元素,则返回true(真)
void clear() *删除集合内的所有元素
boolean contains(Object) 若集合包含自变量,就返回“真”
boolean containsAll(Collection) 若集合包含了自变量内的所有元素,就返回“真”
boolean isEmpty() 若集合内没有元素,就返回“真”
Iterator iterator() 返回一个反复器,以用它遍历集合的各元素
boolean remove(Object) *如自变量在集合里,就删除那个元素的一个实例。如果已进行了删除,就返回
“真”
boolean removeAll(Collection) *删除自变量里的所有元素。如果已进行了任何删除,就返回“真”
boolean retainAll(Collection) *只保留包含在一个自变量里的元素(一个理论的“交集”)。如果已进
行了任何改变,就返回“真”
int size() 返回集合内的元素数量
Object[] toArray() 返回包含了集合内所有元素的一个数组
*这是一个“可选的”方法,有的集合可能并未实现它。若确实如此,该方法就会遇到一个
UnsupportedOperatiionException,即一个“操作不支持”违例,详见第9 章。
下面这个例子向大家演示了所有方法。同样地,它们只对从集合继承的东西有效,一个ArrayList 作为一种
“不常用的分母”使用:
//: Collection1.java
// Things you can do with all Collections
package c08.newcollections;
import java.util.*;
public class Collection1 {
// Fill with 'size' elements, start
237
// counting at 'start':
public static Collection
fill(Collection c, int start, int size) {
for(int i = start; i < start + size; i++)
c.add(Integer.toString(i));
return c;
}
// Default to a "start" of 0:
public static Collection
fill(Collection c, int size) {
return fill(c, 0, size);
}
// Default to 10 elements:
public static Collection fill(Collection c) {
return fill(c, 0, 10);
}
// Create & upcast to Collection:
public static Collection newCollection() {
return fill(new ArrayList());
// ArrayList is used for simplicity, but it's
// only seen as a generic Collection
// everywhere else in the program.
}
// Fill a Collection with a range of values:
public static Collection
newCollection(int start, int size) {
return fill(new ArrayList(), start, size);
}
// Moving through a List with an iterator:
public static void print(Collection c) {
for(Iterator x = c.iterator(); x.hasNext();)
System.out.print(x.next() + " ");
System.out.println();
}
public static void main(String[] args) {
Collection c = newCollection();
c.add("ten");
c.add("eleven");
print(c);
// Make an array from the List:
Object[] array = c.toArray();
// Make a String array from the List:
String[] str =
(String[])c.toArray(new String[1]);
// Find max and min elements; this means
// different things depending on the way
// the Comparable interface is implemented:
System.out.println("Collections.max(c) = " +
Collections.max(c));
System.out.println("Collections.min(c) = " +
Collections.min(c));
// Add a Collection to another Collection
238
c.addAll(newCollection());
print(c);
c.remove("3"); // Removes the first one
print(c);
c.remove("3"); // Removes the second one
print(c);
// Remove all components that are in the
// argument collection:
c.removeAll(newCollection());
print(c);
c.addAll(newCollection());
print(c);
// Is an element in this Collection?
System.out.println(
"c.contains(\"4\") = " + c.contains("4"));
// Is a Collection in this Collection?
System.out.println(
"c.containsAll(newCollection()) = " +
c.containsAll(newCollection()));
Collection c2 = newCollection(5, 3);
// Keep all the elements that are in both
// c and c2 (an intersection of sets):
c.retainAll(c2);
print(c);
// Throw away all the elements in c that
// also appear in c2:
c.removeAll(c2);
System.out.println("c.isEmpty() = " +
c.isEmpty());
c = newCollection();
print(c);
c.clear(); // Remove all elements
System.out.println("after c.clear():");
print(c);
}
} ///:~
通过第一个方法,我们可用测试数据填充任何集合。在当前这种情况下,只是将int 转换成String。第二个
方法将在本章其余的部分经常采用。
newCollection()的两个版本都创建了ArrayList,用于包含不同的数据集,并将它们作为集合对象返回。所
以很明显,除了Collection 接口之外,不会再用到其他什么。
print()方法也会在本节经常用到。由于它用一个反复器(Iterator )在一个集合内遍历,而任何集合都可以
产生这样的一个反复器,所以它适用于List 和Set,也适用于由一个Map 生成的Collection。
main()用简单的手段显示出了集合内的所有方法。
在后续的小节里,我们将比较List ,Set 和Map 的不同实现方案,同时指出在各种情况下哪一种方案应成为
首选(带有星号的那个)。大家会发现这里并未包括一些传统的类,如Vector,Stack 以及Hashtable 等。
因为不管在什么情况下,新集合内都有自己首选的类。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值