|
集合框架概括:
集合代表了一组对象(和数组一样,但数组长度不能变,而集合能)。java中的集合框架定义了一套规范,
用来表示、操作集合,使具体操作与实现细节解藕。
集合框架主要的是“增删改查"
集合的三个特点:
- 集合是用于存储对象的容器
- 集合的长度是可变的
- 集合不可以存储基础数据类型
Collection(采集)接口提供及常用的方法:
Collection c=
new ArrayList();
c.add(1);
- 增:add、addAll
- 删:remove、removeAll、clear
- 改:
- 查:binarySearch(Listlist,T key)、binarySearch(Listlist,T key, Comparator com)
- 最小值:min(Collectionc)、min(Collectionc, Comparator com)
- 最大值:max(Collectionc)、max(Collectionc, Comparator com)
- 排序:sort(Listlist)、sort(Listlist, Comparator com)
- 逆序:reverse(Listlist)
- 乱序:shuffle(List list)
代码演示:
public class Test {
public static void main(String[] args) {
List<Double> list = new ArrayList<Double>();
list.add(33.1);
list.add(11.1);
list.add(22.1);
list.add(55.1);
list.add(44.1);
System.out.println(list);
System.out.println("最大值:"+Collections.max(list));
int index = Collections.binarySearch(list,22.1);
System.out.println("22.1所在位置:"+index);
System.out.println("逆序:");
Collections.reverse(list);
System.out.println(list);
System.out.println("排序:");
Collections.sort(list);
System.out.println(list);
System.out.println("乱序:");
Collections.shuffle(list);
System.out.println(list);
}
}
结果:
[33.1, 11.1, 22.1, 55.1, 44.1]
最大值:55.1
22.1所在位置:2
逆序:
[44.1, 55.1, 22.1, 11.1, 33.1]
排序:
[11.1, 22.1, 33.1, 44.1, 55.1]
乱序:
[33.1, 22.1, 55.1, 11.1, 44.1]
Process finished with exit code 0
Map(映射):
将唯一的键映射到值
map.put(
"第四个数"
,
44
);
结果:
{第一个数=11, 第二个数=22, 第四个数=44, 第三个数=33}
取:
get(K key)
Integer x=map.get("第三个数");
Set(集合):
Set
具有与
Collection
完全一样的接口,只是行为上不同,
Set
不保存重复的元素
Set<Integer> set=newHashSet<Integer>();
结果:
[11, 12, 13]
List:
Vector是“向量”的含义,也就是动态数组。除了实现了接口的方法,还额外提供了set、get、indexOf、subList、size等方法;
Vector<Integer> v1=
new
Vector<Integer>();
Stack(堆栈):
tack继承自Vector,额外增加push、pop、peek等方法;
代码:
public class Test {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(11);
stack.push(22);
stack.push(33);
System.out.println(stack);
System.out.println(stack.peek());
System.out.println(stack);
System.out.println(stack.pop());
System.out.println(stack);
}
}
结果:
[11, 22, 33]
33
[11, 22, 33]
33
[11, 22]
Process finished with exit code 0
LinkedList实现了List,还额外增加了addFirst、addLast、getFirst、
比之前的减省
迭代器(Iterator):
public class Demo {
public static void main(String[] args) { HashSet h=
new HashSet(); h.add(
1); h.add(
2); h.add(
3); h.add(
4); h.add(
5); Iterator i=h.iterator();
while (i.hasNext()){ System.
out.println(i.next()); } } }
|