Thinking in Java——集合(Collection)
一、ArrayList的使用(略)
二、容器的基本概念
(一)、Collection是集合类的基本接口
主要方法:
public interface Collection<E>{
boolean add(E element);//向集合中添加元素,E代表泛型
Iterator<E> iterator();//返回实现了Iterator接口的对象
}
关于:Iterator之后讲解。
(二)、实现了Collection的子类:
List:按照顺序插入保存元素。 Set:该容器内不能有重复的元素 Queue:按照队列的规则决定对象的顺序
(三)、Map接口
定义:一组成对的“键值对”对象,使用key查找value
注:Map这是单独的接口,不属于Collection,所以以map结尾的类都不属于Collection
(四)、根据上诉分析使用容器
1、ArrayList向上转型为Collection,并通过Collection添加处理数据。(运用到的技术:父类引用指向子类对象,调用子类的方法)
public class UpToCollection {
public static void main(String [] args){
ArrayList<Integer> arrayList = new ArrayList();
for(int i=0; i<5; ++i){
arrayList.add(i);
}
Collection<Integer> collection = arrayList;
collection.add(5);
//这里使用了foreach循环,只要实现了Iterator接口就能够使用foreach
//Collection没有List的get方法,需要用Iterator来进行遍历
for(Integer i: collection){
System.out.println(i);
}
}
}
2、添加一组元素
public class AddElementToCollection {
public static void main(String[]args){ Collection<Integer> collection = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6));
//知识点1:利用Arrays这个静态类,将数组,或者一列数字转换为List
//知识点2:ArrayList可以嵌套List创建
/*知识点3:为什么不可以Collection<Integer> collection =
* Arrays.asList(1,2,3,4,5,6);,发现创建并没有问题,但是到下文的时候使用
* collection.addAll(Arrays.asList(datas));是会报错的
* 原因:因为Arrays.asList(1,2,3,4,5,6)创建的List是固定长度的List
* 所以是无法执行add()方法的。
*/
Integer [] datas = {7,8,9,10};
/*知识点4:必须使用Integer作为类,不能使用int,否则会报错
*因为之前Collection<Integer> collection,已经将泛型定为Integer
*所以不能使用引用类型,得到输入的泛型是什么,就需要建立什么类的数组
*/
collection.addAll(Arrays.asList(datas));
for(Integer i: collection){
System.out.println(i);
}
//上文为通过Collection往List中添加一组数据(数组,或者自定义的数据),下文介绍另一种方法 Collections.addAll(collection, 11,12,13,14,15,16);
Collections.addAll(collection, datas);
//注:这是Collections类不是Collection类
}
}
AddElementToCollection
Collection添加元素的方法 优点:方法运行效率快。 缺点:但是需要创建一个Collection类,来作为对象
Collections添加元素的方法 优点:方便,不需要创建Collection类。
3、Collection类型的作用:统一类型添加,删除。。。(统一遍历是由Iterator确定的)
public class CollectionEffect {
//统一各种容器,只需要一种方法就能添加,删除
public static void main(String[] args){
print(fill(new ArrayList<String>()));
print(fill(new HashSet<String>()));
print(fill(new HashMap<String,String>()));
}
//Collection接口的集合
public static Collection<String> fill(Collection<String> c){
c.add("dog");
c.add("cat");
c.add("pig");
return c;
}
//重载fill方法,提供Map接口
public static Map<String,String> fill(Map<String,String> map){
map.put("dog", "pig");
map.put("cat","small"); return map;
} public static void print(Collection<String> c){ } public static void print(Map<String,String> map){ }
}
CollectionEffect
三、迭代器(Iterator)
作用:统一遍历各种容器
接口方法:
public interface Iterator<E>{
E next();//获取下一个元素
boolean hasNext();//查看是否存在下一个元素
void remove();//移除元素
}
Iterator
注意:1.在使用next()方法前需要使用hasNext();
2.next()和remove()是成对存在的。
使用:
public class UseIterator {
public static void main(String[]args){
ArrayList<Integer> arrayList = new ArrayList();
for(int i=0; i<5; ++i){
arrayList.add(i);
}
//获取Iterator,该方法是从Collection接口继承下来的
Iterator<Integer> iterator = arrayList.iterator();
//使用
while(iterator.hasNext()){
Integer x = iterator.next();
System.out.println(x);
iterator.remove();
}
}
}
UseIterator
统一遍历:修改CollectionEffect.java中的print方法,
//...接上文
public static void print(Iterator<String> iterator){
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
CollectionEffect
四、具体的集合
①、ArrayList:可动态增长和缩减的数组,便于搜索,不利于插入和删除。 详解:略。
②、LinkedList:由链表组成的序列,便于插入,和删除,不利于查找。LinkedList还提供了使用其做栈和队列或双端队列的方法。导致LinkedList的Iterator与其他集合不同,所以等会会统一介绍。
让LinkedList实现Stack(已经有了Stack这个类,但是LinkedList可以产生更好的Stack):
public class LinkedListStack<T> {
private LinkedList<T> mLinkedList;
public LinkedListStack(){
mLinkedList = new LinkedList<T>();
}
//入栈
public void push(T view){
mLinkedList.add(view);
}
//获取栈顶元素
public T peek(){
return mLinkedList.getFirst();
}
//移除栈顶元素
public T pop(){
return mLinkedList.removeFirst();
} public boolean isEmpty(){
return mLinkedList.isEmpty();
}
public String toString(){
return mLinkedList.toString();
}
}
LinkedListStack
其他暂不实现。
LinkedList的迭代器ListIterator
1、只能用于各种List类的方法。
2、作用:Iterator只能向前移动,ListIterator可以双向移动。
public class UseListIterator {
public static void main(String[] args){
LinkedList<Integer> linkedList = new LinkedList<Integer>();
for(int i=0; i<10; ++i){
linkedList.add(i);
}
//获取ListIterator
ListIterator<Integer> listIterator = linkedList.listIterator();
//linkedList.listIterator(3); 让Iterator从第三这个位置开始遍历
while(listIterator.hasNext()){
int i = listIterator.next();
System.out.println(i);
//新特性 1:能够修改当前位置的数据
listIterator.set(5);
//特性2:能够向前移动,并获取数据
listIterator.hasPrevious();
listIterator.previous();
}
}
}
UseListIterator
③、Set:不保存重复的元素。
散列集(Hasing):读取数据不按照存储数据时候的排序(随机排序),能够快速查找到所需要的对象。
原理:散列表为每个对象计算一个整数,称为散列码。散列码是由对象实例域产生的整数(具体产生的算法不管)、
注:如果是自定义类,就要负责实现这个类的hashCode,自己实现的hashCode方法要与equals方法兼容(就是如果有一个返回true则全都应该返回true)
在JAVA中散列表由链表数组实现(就是有一串数组,每个数组存放的是一个链表),这串数组中的每个位置叫做“桶”。
桶的作用:解决散列码相同的情况、当散列码相同的时候就将该数据放入桶的链表中。之后查询到该桶的时候遍历该桶的链表。
小知识:当插入的数据太多,有可能导致桶被沾满的情况,所以当桶被占用超过75%的时候,就会进行再散列(创建新的表增加桶的数量,将旧表的数据移到新表)。
树集(Tree):是一个有序集合,可以用任何顺序将元素插入到集合中,但遍历取出的时候,每个值自动按照排序后的顺序实现。(每将一个元素添加到树中,都被放置到正确的位置)
问:Tree如何知道希望每个元素怎样排列?
重写Comparator接口,并传入到TreeSet<E>中。
public class UseTreeSet {
public static void main(String[]args){
//为TreeSet添加比较的逻辑
Comparator<Integer> compatator = new Comparator(){ @Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
//这里写逻辑
return 0;
} };
TreeSet<Integer> treeSet = new TreeSet(compatator);
}
}
UseTreeSet
所以说:要使用TreeSet的步骤是①、创建类并实重写equal()和hashCode()②、创建Comparator接口,并重写coparator()方法 ③、将Comparator对象传入TreeSet中
队列(Queen):ArrayDeque和LinkedList实现。且这两个类都实现了双端队列(就是在链表的头尾都可进行添加和删除),LinkedList实现了Queue接口ArrayDeque实现了Deque接口。同时还有一个特殊的队列“优先级队列(Priority queue)”,任意插入,按照优先级的排列进行读取。(优先级是跟Tree一样,通过重写Coparator接口来进行排序的,如果没有重写Coparator则进行自然排序——调用对象equal()方法)。
映射表(Map):通过自己设置的键(key)查找对应的值(value)。因为Map不属于Collection那么,如何遍历Map的key,或Map的value,还有key与value同时遍历
1、遍历键的信息
HashMap<String,String> map = new HashMap();
map.put("123","asda");
map.put("234","zxczxc");
map.put("asd", "zxcdd");
//遍历Map中的所有键
Set<String> set = map.keySet();//通过获取Set映射表中的所有的键
//注:该Set不是HashSet也不是TreeSet,只是实现了Set接口的类
for (String str : set){
System.out.println(str);
}
遍历键的信息
2、遍历值的信息
//接上
//遍历所有值
Collection<String> collection = map.values();//获取Collection获取值
for (String str : collection){
System.out.println(str);
}
遍历值
3、全部遍历
//全部遍历
for (Map.Entry<String,String> mapData : map.entrySet()){
String key = mapData.getKey();
String value = mapData.getValue();
}
五、自定义Collection和Iterator
1、通过继承Collection接口实现方法 缺点:Collection需要重写的方法太多了,需要耗费大量的精力
2、所以JAVA提供了AbstactCollection方法,完成了大部分Collection方法 缺点:当一个类已经继承其他类的时候,必须重写Collection。
3、直接重写Iterator接口。
Thinking in Java——集合(Collection)的更多相关文章
- java集合——Collection接口
Collection是Set,List接口的父类接口,用于存储集合类型的数据. 2.方法 int size():返回集合的长度 void clear():清除集合里的所有元素,将集合长度变为0 Ite ...
- Java 集合Collection与List的详解
1.什么是集合 存储对象的容器,面向对象语言对事物的体现都是以对象的形式,所以为了方便对多个对象的操作,存储对象,集合是存储对象最常用的一种方式. 集合的出现就是为了持有对象.集合中可以存储任意类型的 ...
- Java 集合-Collection接口和迭代器的实现
2017-10-30 00:30:48 Collection接口 Collection 层次结构 中的根接口.Collection 表示一组对象,这些对象也称为 collection 的元素.一些 c ...
- Java集合Collection基本方法
jdk1.7 api中的方法摘要: 参考java集合大全图:https://www.cnblogs.com/xkzhangsanx/p/10889114.html Collection为List.Se ...
- JAVA集合--Collection接口
本文首发于cartoon的博客 转载请注明出处:https://cartoonyu.github.io/cartoon-blog 在概述里面也说过:Collection是jav ...
- 「 深入浅出 」java集合Collection和Map
本系列文章主要对java集合的框架进行一个深入浅出的介绍,使大家对java集合有个深入的理解. 本篇文章主要具体介绍了Collection接口,Map接口以及Collection接口的三个子接口Set ...
- java: 集合collection
collection是集合层次结构中的根接口,一些集合允许重复元素,而其他集合不允许. 有些collection是有序的,而另一些是无序的. JDK不提供此接口的任何直接实现:它提供了更具体的子接口的 ...
- Java集合 Collection、Set、Map、泛型 简要笔记
集合 什么是集合 概念 对象的容器,实现了对对象常用的操作 和数组的区别 数组长度固定,集合长度不固定 数组可以存储基本类型和引用类型,集合只能存储引用类型 位置 java.util.*; Colle ...
- Java 集合Collection——初学者参考,高手慎入(未完待续)
1.集合简介和例子 Collection,集合.和数学定义中的集合类似,把很多元素放在一个容器中,方便我们存放结果/查找等操作. Collection集合实际上是很多形式集合的一个抽象. 例如十九大就 ...
随机推荐
- MVC 模型、视图、控制及其单入口文件的mvc的工作原理
什么是mvc,mvc就是模型视图控制,模型就是model,在项目中负责数据库相关的操作,视图就是view ,负责页面的展示和数据的展示,控制就是controller ,负责中间的逻辑转换,数 ...
- Java 一个字符串在另外一个字符串出现次数
统计一个字符串在另外一个字符串出现次数 代码如下: package me.chunsheng.javatest; import java.util.regex.Matcher; import java ...
- ActionSupport.getText()方法 以及 js中:<s:text name="" />
下面略述com.opensymphony.xwork2.ActionSupport.getText()方法 public String getText(String aTextName) 说明:Get ...
- jQuery模拟瀑布流布局
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- Asp.net Web.Config - 配置元素customErrors
Asp.net配置文件的配置方式,其实在MSDN里面是写得最清楚的了.可惜之前一直未曾了解到MSDN的强大. 先贴个地址:http://msdn.microsoft.com/zh-cn/library ...
- C# 获取当前应用程序的绝对路径支持asp.net
Asp.net在类库中获取某文件的绝对路径.这个问题在初学的时候就经常碰到过,经常是查了忘,忘了查.浪费了大量的今天专门写个文章,以后到这里查.有时间顺便记得研究下这个东西. 在主程序目录就不说了 ...
- Fatal error: Allowed memory size of 8388608 bytes exhausted
这两天安装bugfree,更换了一个数据量较大的库,结果打开bug详情页要么是空白页,要么就报如题的错误,错误信息还包括C:\wamp\www\bugfree\Include\Class\ADOLit ...
- 【转】6.4.6 将驱动编译进Linux内核进行测试
原文网址:http://www.apkbus.com/android-98520-1-1.html 前面几节都是将Linux驱动编译成模块,然后动态装载进行测试.动态装载驱动模块不会随着Android ...
- bzoj3407 [Usaco2009 Oct]Bessie's Weight Problem 贝茜的体重问题
Description 贝茜像她的诸多姊妹一样,因为从约翰的草地吃了太多美味的草而长出了太多的赘肉.所以约翰将她置于一个及其严格的节食计划之中.她每天不能吃多过H(5≤日≤45000)公斤的干 ...
- UESTC_One Step Two Steps CDOJ 1027
As we all know,the handsome boy, Zcat, has a fever of flat shoes. He sings it on the class, in the d ...