目录
一、集合框架的概述
二、集合框架(Java集合可分为Collection 和 Map 两种体系)
三、Collection接口中的方法的使用
四、集合元素的遍历操作
A. 使用(迭代器)Iterator接口B. jdk5.0新增foreach循环,用于遍历集合、数组
五、Collection子接口之一:List接口
List接口方法ArrayList的源码分析:JDK 7情况下:JDK 8中ArrayList的变化:LinkedList的源码分析:
Vector的源码分析:
六、Collection子接口之一:Set接口
一、Set接口概述
二、set接口的框架:
三、Set的三个实现类
重写hashCode()方法的基本原则
一、集合框架的概述
背景:一方面,面向对象语言对事物的体现都是以对象的形式,为了方便对多个对象的操作,就要对对象进行存储,另一方面,使用Array存储对象方面具有一些弊端,而Java集合就像一种容器,可以动态的把多个对象的引用放入容器中。
1.集合、数组都是对多个数据进行存储操作的结构,简称Java容器。
说明:此时的存储,主要指的是内存层面的存储,不涉及到持久化的存储(.txt,.jpg,.avi,数据库中)
2. 数组在存储多个数据方法的特点:
> 一旦初始化以后,其长度就确定了。
> 数组一旦定义好,其元素的类型也就确定了。我们也就只能操作指定类型的数据了。
比如:String[] arr;int[] arr1;Object[] arr2(多态:数组中也可存放子类类型的数据(String等));
3. 数组在存储多个数据方面的缺点:
> 一旦初始化以后,其长度就不可修改。
> 数组中提供的方法非常有限,对于添加、删除、插入数组等操作,非常不便,同时效率不高
> 获取数组中实际元素的个数的需求,数组没有现成的属性或方法可用
> 数组存储数据的特点:有序、可重复。对于无序、不可重复的需求,不能满足
二、集合框架(Java集合可分为Collection 和 Map 两种体系)
A. Collection接口:单列集合,用来存储一个一个的对象
a.List接口:存储有序的、可重复的数据。--->"动态"数组
|---ArrayList、LinkedList、Vector
b.Set接口:存储无序的、不可重复的数据 --->高中讲的"集合"
|---HashSet、LinkedHashSet、TreeSet
B. Map接口:双列集合,用来存储一对(key - value)一对的数据 --->高中函数:y = f(x)
|---HashMap、LinkedHashMap、TreeMap、Hashable、Properties
三、Collection接口中的方法的使用
public void test1(){Collection coll = new ArrayList();//add(Object e):将元素e添加到集合coll中coll.add("AA");coll.add("BB");coll.add(123);//自动装箱coll.add(new Date());//size():获取添加的元素的个数System.out.println(coll.size());//4//addAll(Collection coll1):将coll1集合中的元素添加到当前的集合中Collection coll1 = new ArrayList();coll1.add(456);coll1.add("CC");coll.addAll(coll1);System.out.println(coll.size());//6 System.out.println(coll);//clear():清空集合元素(对象还在,只是元素没了) coll.clear();//isEmpty():判断当前集合是否为空System.out.println(coll.isEmpty());}//结论:向Collection接口的实现类的对象中添加数据obj时,要求obj所在类要重写equals().
public void test2(){Collection coll = new ArrayList();coll.add(123);coll.add(456);coll.add(new Person("Jerry",20));coll.add(new String("Tom"));coll.add(false);//1.contains(Object obj):判断当前集合中是否包含obj//我们在判断时会调用obj对象所在类的equals() boolean contains = coll.contains(123);System.out.println(contains);System.out.println(coll.contains(new String("Tom")));//true System.out.println(coll.contains(new Person("Jerry",20)));//false-->ture//2.containsAll(Collection coll1):判断形参coll1中的所有元素是否都存在于当前集合中Collection coll1 = Arrays.asList(123,456);System.out.println(coll.containsAll(coll1));}
public void test3(){//3.remove(Object obj):从当前集合中移除obj元素Collection coll = new ArrayList();coll.add(123);coll.add(456);coll.add(new Person("Jerry",20));coll.add(new String("Tom"));coll.add(false);coll.remove(1234);System.out.println(coll);//[123, 456, Person{name='Jerry', age=20}, Tom, false]coll.remove(new Person("Jerry",20));System.out.println(coll);//[123, 456, Tom, false]//4.removeAll(Collection coll1)://从当前集合中移除coll1中所有的元素Collection coll1 = Arrays.asList(123,4567);coll.removeAll(coll1);System.out.println(coll);//[456, Tom, false]}public void test4(){Collection coll = new ArrayList();coll.add(123);coll.add(456);coll.add(new Person("Jerry",20));coll.add(new String("Tom"));coll.add(false);//5.retainAll(Collection coll1):获取带那个前集合和coll1集合的交集,并返回给当前集合// Collection coll1 = Arrays.asList(123.456,789);// coll.retainAll(coll1);// System.out.println(coll);//6.equals(Object obj):要想返回true,需要当前集合和形参集合的元素都相同Collection coll1 = new ArrayList();coll1.add(123);coll1.add(456);coll1.add(new Person("Jerry",20));coll1.add(new String("Tom"));coll1.add(false);System.out.println(coll.equals(coll1));//true}public void test5(){Collection coll = new ArrayList();coll.add(123);coll.add(456);coll.add(new Person("Jerry",20));coll.add(new String("Tom"));coll.add(false);//7.hashCode():返回当前对象的哈希值System.out.println(coll.hashCode());//8.集合 --> 数组:toArray() Object[] arr = coll.toArray();for(int i = 0;i < arr.length;i++){System.out.println(arr[i]);}//拓展:数组 --> 集合:调用Arrays类的静态方法asList() List
四、集合元素的遍历操作
A. 使用(迭代器)Iterator接口
1.内部的方法:hasNext() 和 next()
2.集合对象每次调用iterator()方法都得到一个全新的迭代器对象,默认游标都在集合的第一个元素 之前。
3.内部定义了remove().可以在遍历的时候,删除集合中的元素,此方法不同于集合直接调用 remove()注意:在调用it.next()方法之前必须要调用it.hasNext()进行检测,若不调用,且下一条记录无效,直接调用it.next()会抛出NoSuchEiementException异常。
public class IteratorTest {@Test public void test1(){Collection coll = new ArrayList();coll.add(123);coll.add(456);coll.add(new Person("Jerry",20));coll.add(new String("Tom"));coll.add(false);Iterator iterator = coll.iterator();//方式一:不推荐// System.out.println(iterator.next());// System.out.println(iterator.next());// System.out.println(iterator.next());// System.out.println(iterator.next());// System.out.println(iterator.next());//报异常:NoSuchElementException// System.out.println(iterator.next());//方式二:不推荐// for(int i = 0;i < coll.size();i++){// System.out.println(iterator.next());// }//方式三:推荐//hasNext():判断是否还有下一个元素while (iterator.hasNext()){//next():A 指针下移 B 将下移以后集合位置上的元素返回System.out.println(iterator.next());}}@Test public void test2(){Collection coll = new ArrayList();coll.add(123);coll.add(456);coll.add(new Person("Jerry",20));coll.add(new String("Tom"));coll.add(false);
//错误方式一:
// Iterator iterator = coll.iterator();// while((iterator.next()) != null){// System.out.println(iterator.next());//456 Tom//跳着输出// }//还会报异常:NoSuchElementException
//错误方式二:
//集合对象每次调用iterator()方法都得到一个全新的迭代器对象,默认游标都在集合的第一个元素之前。
// while(coll.iterator().hasNext()){// System.out.println(coll.iterator().next());//123死循环// }}//测试Iterator中的remove()@Test public void test3(){Collection coll = new ArrayList();coll.add(123);coll.add(456);coll.add(new Person("Jerry",20));coll.add(new String("Tom"));coll.add(false);//删除集合中的"Tom"Iterator iterator = coll.iterator();while(iterator.hasNext()){Object obj = iterator.next();if("Tom".equals(obj)){iterator.remove();}}//遍历集合iterator = coll.iterator();while (iterator.hasNext()){System.out.println(iterator.next());}}}
B. jdk5.0新增foreach循环,用于遍历集合、数组
@Test//访问Collection public void test1(){Collection coll = new ArrayList();coll.add(123);coll.add(456);coll.add(new Person("Jerry",20));coll.add(new String("Tom"));coll.add(false);//for(集合元素的类型 局部变量:集合对象)//内部仍然调用了迭代器for(Object obj : coll){System.out.println(obj);}}@Test//访问数组public void test2(){int[] arr = new int[]{1,3,4,5,6};//for(数组元素的类型 局部变量:数组对象) for(int i : arr){System.out.println(i);}}一道笔试题//笔试题@Test public void test3(){String[] arr = new String[]{"MM","MM","MM"};//方式一:普通for赋值//输出:GG//拿着数组修改,数组存储在堆中,可修改// for(int i = 0;i < arr.length;i++){// arr[i] = "GG";// }//方式二:增强for循环//输出:MM//将数组中的元素一个个赋给字符型变量s,而s存储在常量区,不可被修改for(String s : arr){s = "GG";}for(int i = 0;i < arr.length;i++){System.out.println(arr[i]);}}
五、Collection子接口之一:List接口
简介:鉴于Java中数组用来存储数据的局限性,我们通过使用List代替数组List集合类中元素有序、且可重复,集合中的每个元素都有其对应的顺序索引。
List容器中的元素都对应一个整型的序号记载其在容器中的位置,可以根据序号存取容器中的元素。
List接口方法
public void test1(){ArrayList list = new ArrayList();list.add(123);list.add(456);list.add("AA");list.add(new Person("Jerry",20));list.add(456);System.out.println(list);//[123, 456, AA, Person{name='Jerry', age=20}, 456]
//void add(int index,Object ele):在index位置插入ele元素list.add(1,"BB");System.out.println(list);//[123, BB, 456, AA, Person{name='Jerry', age=20}, 456]
//boolean addAll(int index,Collection eles):从index位置上开始将eles中的所有元素添加进来List list1 = Arrays.asList(1,2,3);list.addAll(list1);System.out.println(list.size());//9
//Object get(int index):获取指定index位置的元素System.out.println(list.get(0));//123}public void test2(){ArrayList list = new ArrayList();list.add(123);list.add(456);list.add("AA");list.add(new Person("Jerry",20));list.add(456);
//int indexOf(Object obj):返回obj在集合中首次出现的位置,如果不存在,返回-1 int index = list.indexOf(4567);System.out.println(index);//-1
//int LastIndexOf(Object obj):返回obj在当前集合中末次出现的位置System.out.println(list.lastIndexOf(456));//4
//Object remove(int index):移除指定index位置的元素,并返回此元素Object obj = list.remove(0);//123 System.out.println(list);//[456, AA, Person{name='Jerry', age=20}, 456]
//Object set(int index,Object ele):设置指定index位置的元素为ele list.set(1,"CC");//[456, CC, Person{name='Jerry', age=20}, 456]System.out.println(list);////List subList(int formIndex,int toIndex):返回从formIndex到toIndex位置的左闭右开的子集合List subList = list.subList(2,4);System.out.println(subList);//[Person{name='Jerry', age=20}, 456]System.out.println(list);//[456, AA, Person{name='Jerry', age=20}, 456]}遍历List的方式public void test3(){ArrayList list = new ArrayList();list.add(123);list.add(456);list.add("AA");//方式一:Iterator迭代器的方式Iterator iterator = list.iterator();while(iterator.hasNext()){System.out.println(iterator.next());}//方式二:增强for循环for(Object obj : list){System.out.println(obj);}//方式三:普通for循环for(int i = 0;i < list.size();i++){System.out.println(list.get(i));}区分List中remove(int index)和remove(Object obj)@Test public void test4(){ArrayList list = new ArrayList();list.add(1);list.add(2);list.add(3);updateList(list);System.out.println(list);}public static void updateList(List list){list.remove(2);//[1, 2]//删掉角标为2的元素list.remove(new Integer(2));//删掉字符2}面试题:ArrayList、LinkedList、Vector三者的异同?
同:三个类都是实现了List接口,存储数据的特点相同:存储有序的、可重复的数据
不同: |---ArrayList:作为List接口的主要实现类:线程不安全的,效率高;底层使用Object[] elementData存储
|---LinkedList:对于频繁的插入、删除操作,使用此类效率比ArrayList高;底层使用双向链表存 储
|---Vector:作为List接口的古老的实现类;线程安全的,效率低;底层使用Object[] elementData存储ArrayList的源码分析:
JDK 7情况下:
ArrayList list = new ArrayList();//底层创建了长度是10的Object[]数组elementData
list.add(123);//elementData[0] = new Integer(123);
...
List.add(11);//如果此次的添加导致底层elementData数组容量不够,则扩容。
默认情况下,扩容为原来的容量的1.5倍,同时需要将原有的数组中的数据复制到新的数组中。
结论:建议开发中使用带参的构造器:ArrayList list = new ArrayList(int capacity)
JDK 8中ArrayList的变化:
ArrayList list = new ArrayList();//底层Object[] elementData初始化为{}.并没有创建长度为10的数组
list.add(123);//第一次使用add()时,底层才创建了长度为10的数组,并将数据123添加到elementData[0]
后续的添加和扩容操作与JDK 7相同小结:jdk7中的ArrayList的对象的创建类似于单例的饿汉式,而jdk8中的ArrayList的对象的创建类似于单例的懒汉式,延迟了数组的创建,节省内存LinkedList的源码分析:
LinkedList list = new LinkedList();内部没有声明数组,而是声明了Node类型的first和last属性,默认值为null
list.add(123);//将123封装到Node中,创建了Node对象。
其中,Node定义为:体现了LinkedList的双向链表的说法private static class Node
Vector的源码分析:
jdk7和jdk8中通过Vector()构造器创建对象时,底层都创建了长度为10的数组在扩容方面,默认扩容为原来的数组长度的2倍。
六、Collection子接口之一:Set接口
一、Set接口概述
> Set接口是Collection的子接口,set接口没有提供额外的方法> Set集合不允许包含相同的元素,如果试把两个相同的元素加入同一个Set集合中,则添加操作失败。
> Set判断两个对象是否相同不是使用 == 运算符,而是根据 equals() 方法> 注意点:1.Set接口中没有额外定义新的方法,使用的都是Collection中声明过的方法。
2.要求:向Set中添加的数据,其所在的类一定要重写hashCode()和equals()
要求:重写的hashCode()和equals()尽可能保持一致性:相等的对象必须是具有相等的数列码
重写两个方法的小技巧:对象中用作equals()方法比较的Field,都应该用来计算hashCode值
二、set接口的框架:
Collection接口:单列集合,用来存储一个一个的对象
> Set接口:存储无序的、不可重复的数据 --->高中讲的"集合"
A.HashSet:作为Set接口的主要实现类:线程不安全的,可以存储null值
B.LinkedHashSet:作为HashSet的子类:遍历其内部数据时,可以按照添加的顺序遍历
对于频繁的遍历操作,LinkedHashSet效率高于HashSet
C.TreeSet:可以按照添加对象的指定属性,进行排序
三、Set的三个实现类
重写hashCode()方法的基本原则> 在程序运行时,同一个对象多次调用hashCode()方法应该返回相同的值。
> 当两个对象的equals()方法比较返回true时,这两个对象的hashCode()方法的返回值也应相等> 对象中用作equals()方法比较的Field,都应该用来计算hashCode值。
public void test1(){HashSet set = new HashSet();set.add(456);set.add(123);set.add(123);set.add("AA");set.add("CC");set.add(new User("Tom",12));set.add(new User("Tom",12));set.add(129);Iterator iterator = set.iterator();while(iterator.hasNext()){System.out.println(iterator.next());// AA// CC// 129// 456// 123// User{name='Tom', age=12}}Set:存储无序的、不可重复的数据
以HashSet为例说明:
1.无序性:不等于随机性。存储的数据在底层数组中并非按照数组索引的顺序添加,而是根据数据的哈希值决定的
2.不可重复性:保证添加的元素按照equals()判断时,不能返回true.即:相同的元素只添加一个
二、添加元素的过程:以HashSet为例:
我们向HashSet中添加元素a,首先调用元素a所在类的hashCode()方法,计算元素a的哈希值,此哈希值接着通过
某种算法计算出在HashSet底层数组中的存放位置(即为:索引位置),判断此位置上是否已经有元素:
如果此位置上没有其他元素,则元素a添加成功。--->情况1
如果此位置上有其他元素b(或以链表形式存在的多个元素),则比较元素a与元素b的has值。
如果hash值不相同,则元素a添加成功。---->情况2
如果hash值相同,进而需要调用元素a所在类的equals()方法:
equals()返回true,元素a添加失败
equals()返回false,则元素a添加成功。----情况3
对于添加成功的情况2和情况3而言:元素a与已经存在指定索引位置上数据以链表的方式存储。
JDK 7:元素a放到数组中,指向原来的元素。
LDK 8:原来的元素在数组中,指向元素a
总结:七上八下
HashSet底层:数组 + 链表的结构(前提:JDK 7之前)
LinkedHashSet的使用
linkedHashSet作为HashSet的子类,在添加数据的同时,每个数据还维护了两个引用,记录此数据前一个数据和后一个数据
优点:对于频繁的遍历操作,LinkedHashSet效率高于HashSet
public void test2(){HashSet set = new LinkedHashSet();set.add(456);set.add(123);set.add(123);set.add("AA");set.add("CC");set.add(new User("Tom",12));set.add(new User("Tom",12));set.add(129);Iterator iterator = set.iterator();while(iterator.hasNext()) {System.out.println(iterator.next());}}
注意点:
1.向TreeSet中添加的数据,要求是相同类的对象。
2.两种排序方式:自然排序(实现Comparable接口) 和 定制排序(Comparator)
3.自然排序中,比较两个对象是否相同的标准为:compareTo()返回0.不再是equals().
定制排序中,比较两个对象是否相同的标准为:compare()返回0.不再是equals().
4.TreeSet和后面要讲的TreeMap采用红黑树的存储结构;特点:有序,查询速度比List快public void test1(){TreeSet set = new TreeSet();//报错:ClassCastException 不能添加不同类的对象// set.add(123);// set.add(456);// set.add("AA");// set.add(new User("Tom",12));
//举例一:
// set.add(34);// set.add(-34);// set.add(43);// set.add(11);// set.add(8);
//举例二:
set.add(new User("Tom",12));set.add(new User("Jerry",32));set.add(new User("Jim",2));set.add(new User("Mike",65));set.add(new User("Jack",22));set.add(new User("Jack",62));Iterator iterator = set.iterator();while(iterator.hasNext()){System.out.println(iterator.next());}}@Test public void test2(){Comparator com = new Comparator() {@Override public int compare(Object o1, Object o2) {if(o1 instanceof User && o2 instanceof User){User u1 = (User)o1;User u2 = (User)o2;return Integer.compare(u1.getAge(),u2.getAge());}else{throw new RuntimeException("输入的类型不匹配");}}};TreeSet set = new TreeSet(com);set.add(new User("Tom",12));set.add(new User("Jerry",32));set.add(new User("Jim",22));set.add(new User("Mike",65));set.add(new User("Jack",22));set.add(new User("Jack",62));Iterator iterator = set.iterator();while(iterator.hasNext()){System.out.println(iterator.next());}}到此这篇关于深入浅出讲解Java集合之Collection接口的文章就介绍到这了,更多相关Java Collection内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:关于Java集合框架Collection接口详解java集合collection接口与子接口及实现类Java集合的Collection接口和List接口详解Java集合框架之Collection接口详解java Collection集合接口的介绍和使用详解
