黑马程序员——Java语言:集合

来源:互联网 发布:12123app网络请求失败 编辑:程序博客网 时间:2024/06/14 07:47

------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------

一、集合框架

集合类的由来:

对象用于封装特有数据,对象多了需要存储;如果对象的个数不确定,就使用集合容器进行存储。

集合特点:

1. 用于存储对象的容器。

2. 集合的长度是可变的。

3. 集合中不可以存储基本数据类型值。

集合容器因为内部的数据结构不同,有多种具体容器。

不断的向上抽取,就形成了集合框架。

P.S.

数组和集合类同是容器,有何不同?

数组虽然也可以存储对象,但长度是固定的;集合长度是可变的。

数组中可以存储基本数据类型,集合只能存储对象。


1.1 Collection接口

Collection 层次结构中的根接口

Collection的常见方法:

1、添加:

boolean add(Object obj);

boolean addAll(Collection coll);

2、删除:

boolean remove(Object obj);

boolean removeAll(Collection coll);

void clear();

3、判断:

boolean contains(Object obj);

boolean containsAll(Collection coll);

boolean isEmpty();判断集合中是否有元素。

4、获取:

int size();

Iterator iterator();

取出元素的方式:迭代器。该对象必须依赖于具体容器,因为每一个容器的数据结构都不同,所以该迭代器对象是在容器中进行内部实现的,也就是iterator方法在每个容器中的实现方式是不同的。对于使用容器者而言,具体的实现不重要,只要通过容器获取到该实现的迭代器的对象即可,也就是iterator方法。

Iterator接口就是对所有的Collection容器进行元素取出的公共接口。

5、其他:

boolean retainAll(Collection coll);取交集

Object[] toArray();将集合转成数组

练习:

import java.util.*;class CollectionDemo{public static void main(String[] args){method1();sop("-----------------");method2();sop("-----------------");method_get();}public static void method1(){//创建一个集合容易,使用Collection接口的子类ArrayList al = new ArrayList();//1.添加元素al.add("java1");al.add("java2");al.add("java3");al.add("java4");sop(al);//2.删除元素al.remove("java2");//al.clear();// 清空集合//3.获取个数,集合长度sop("size:"+al.size());sop(al);//4.判断元素sop("java3是否存在:"+al.contains("java3"));sop("集合是否为空:"+al.isEmpty());}public static void method2(){ArrayList a1 = new ArrayList();ArrayList a2 = new ArrayList();a1.add("java1");a1.add("java2");a1.add("java3");a1.add("java4");a2.add("java1");a2.add("java22");a2.add("java5");a2.add("java6");//a1.retainAll(a2);//取交集:a1中只会保留和a2中相同的元素a1.removeAll(a2);//去交集sop("a1:"+a1);sop("a2:"+a2);}public static void method_get(){ArrayList a1 = new ArrayList();a1.add("java1");a1.add("java2");a1.add("java3");a1.add("java4");//Iterator it = a1.iterator();//获取迭代器,用于取出集合中的子元素/*while(it.hasNext()){sop(it.next());}*/for(Iterator it = a1.iterator();it.hasNext();){sop(it.next());}}public static void sop(Object obj){System.out.println(obj);}}

二、ListSet

Collection

|--List :元素是有序的,元素可以重复,因为该集合体系有索引

|--ArrayList 底层的数据结构使用的是数组结构。特点:查询速度快,但是增删慢。 线程不同步

|--LinkedList 底层使用的是链表数据结构。特点:增删快,查询慢

|--Vector 底层是数组数据结构,线程同步,被ArrayList替代

|--Set: 元素是无需的,元素不可以重复

2.1 List

List:特有方法:凡是可以操作角标的方法都是该体系特有的方法

 add(index,element)

    addAll(index,Collection)

 remove(index)

 set(index,element)

 get(index)

   subList(from,to)

   listIterator()

   indexOf();

   lastIndexOf();

练习:

import java.util.*;class ListDemo{public static void main(String[] args){ArrayList al = new ArrayList();al.add("java1");al.add("java2");al.add("java3");sop("原集合:"+al);al.add(1,"java9");sop("add集合:"+al);al.remove(2);sop("remove集合:"+al);al.set(2,"java00");sop("set集合:"+al);sop("al(1):"+al.get(1));for(int x=0;x<al.size(); x++){System.out.println("al("+x+"):"+al.get(x));}Iterator it = al.iterator();while(it.hasNext()){sop("next:"+it.next());}}public static void sop(Object obj){System.out.println(obj);}}

2.1.1 ListIterator

1、概述

ListIteratorList集合特有的迭代器,是Iterator的子接口。在迭代时,不可以通过集合对象的方法操作集合中的元素。因为会发生ConcurrentModificationException异常。所以在迭代器时,只能用迭代器的方法操作元素。可是Iterator方法是有限的,只能对元素进行判断,取出,删除的操作。如果想要其他的操作,如添加、修改等,就需要使用其子接口:ListIterrator。该接口只能通过List集合的ListIterator方法获取。

2ListIterator特有的方法

add(obj);//增加

set(obj);//修改为obj

hasPrevious();//判断前面有没有元素

previous();//取前一个元素

2.1.2 ArrayListVectorLinkedList

LinkedList 特有方法

addFirst()

addLast()

getFirst()

getLast() 

获取元素,如果集合为空,出现NoSuchElementException

removeFirst() 

reomveLast() 

取出并删掉,如果集合为空,出现NoSuchElementException

jkd1.6出现替代方法

offerFirst()

offerLast()

peekFirst()

peekLast()

获取元素,如果集合为空,返回null

pollFirst()

pollLast()

获取并移除,如果集合为空返回null

1、练习基本功能:

import java.util.*;class LinkedListDemo{public static void main(String[] args){LinkedList l = new LinkedList();l.addFirst("java1");l.addFirst("java2");l.addFirst("java3");l.addFirst("java4");sop(l.size());sop(l.removeFirst());sop(l.size());sop(l);while(!l.isEmpty()){sop(l.removeFirst());}}public static void sop(Object obj){System.out.println(obj);}}

3、去除ArrayList中重复的元素

import java.util.*;class ArrayListTest{public static void main(String[] args){ArrayList al = new ArrayList();al.add("java1");al.add("java1");al.add("java2");al.add("java2");al.add("java3");sop(al);al = singleElement(al);sop(al);}public static ArrayList singleElement(ArrayList al){ArrayList newal = new ArrayList();Iterator it = al.iterator();while(it.hasNext()){Object obj = it.next();if(!newal.contains(obj)){newal.add(obj);}}return newal;}public static void sop(Object obj){System.out.println(obj);}}



2.2 Set

Set元素不可以重复,是无序。

Set接口中的方法和Collection一致。

|--HashSet:内部数据结构是哈希表,是不同步的。

|--TreeSet:可以对Set集合中的元素进行排序,是不同步的。

 

2.2.1 HashSet

如何保证元素的唯一性:hashCodeequals

如果元素的hashCode值相同,才会判读equals是否为true

如果元素的hashCode值不同,就不会调用equals

注意,对于判读元素是否存在或者删除等操作,依赖的是元素的hashCodeequals方法

/*往HashSet集合中存入自定义对象姓名和年龄相同为同一个人,为重复元素*/import java.util.*;class HashSetTest{public static void main(String[]args){HashSet hs = new HashSet();hs.add(new Person("a",11));hs.add(new Person("b",12));hs.add(new Person("c",13));hs.add(new Person("d",14));//hs.add(new Person("d",14)); sop("a:"+hs.contains(new Person("a",11)));Iterator it = hs.iterator();while(it.hasNext()){Person p = (Person)it.next();sop(p.getName()+".."+p.getAge());}}public static void sop(Object obj){System.out.println(obj);}}class Person{private String name;private int age;Person(String name, int age){this.name = name;this.age = age;} public int hashCode() { System.out.println(this.name+"....hashCode"); return name.hashCode()+age*2; //保证哈希值唯一 } public boolean equals(Object obj){if(!(obj instanceof Person))return false;Person p = (Person)obj;System.out.println(this.name+"..equals.."+p.name);return this.name.equals(p.name) && this.age == p.age;} public String getName(){return name;}public int getAge(){return age;}}


2.2.2 TreeSet 

可以对Set集合中的元素进行排序,底层数据结构是二叉树。

保证元素唯一性的依据:compareTo方法

1、TreeSet排序的第一种方式:让元素自身具备比较性,

元素需要实现compareable接口,覆盖compareTo方法

这种方法也称为元素的自然顺序,或者叫做默认顺序

2、TreeSet排序的第二种方式:当元素自身不具备比较性

或者具备的比较性不是所需要的,这时就需要让集合自身具备比较性

集合初始化时就已经有了比较方式

下面的代码就实现的元素的比较性和集合的比较性

import java.util.*;class TreeSetDemo2{public static void main(String[] args){TreeSet ts = new TreeSet(new Compare());ts.add(new Student("haha12",1));ts.add(new Student("hehe2442",2));ts.add(new Student("adffg",3));ts.add(new Student("abffg",3));ts.add(new Student("adffg",5));Iterator it = ts.iterator();while(it.hasNext()){Student stu = (Student)it.next();System.out.println(stu.getName()+"..."+stu.getAge());}}}class Student implements Comparable //该接口强制让学生具备比较性{private String name;private int age;Student(String name, int age){this.name = name;this.age = age;}public int compareTo(Object obj){if(!(obj instanceof Student))throw new RuntimeException("不是学生对象");Student s = (Student)obj;if(this.age>s.age)return 1;if(this.age==s.age){return this.name.compareTo(s.name);}return -1;}public String getName(){return name;}public int getAge(){return age;}}class Compare implements Comparator{public int compare(Object o1,Object o2){Student s1 = (Student)o1;Student s2 = (Student)o2;int num = s1.getName().compareTo(s2.getName());if(num==0){return new Integer(s1.getAge()).compareTo(s2.getAge());}return num;}}

三、Map

接口 Map<K,V>

Map集合:该集合存储键值对,而且要保证键的唯一性,一次添加一对元素.

Map

     |--Hashtable 底层是哈希表数据结构,不可以存入nullnull值,该集合线程同步

     |--HashMap 底层是哈希表数据机构,允许使用 null 值和 null 键。该集合不同步,效率高

     |--TreeMap 底层是二叉树结构,不同步,可以用于给Map集中的键排序

Set很像,其实Set底层就是使用了Map集合

1.添加

V put(K key, V value)    添加相同键的值时,新的值会覆盖旧的值,并返回旧值

void putAll(Map<? extends K,? extends V> m)  

2.删除

void clear() 

V remove(Object key)  

3.判断

boolean containsKey(Object key) 

boolean containsValue(Object value) 

boolean isEmpty()  

4.获取

V get(Object key) 

int size()  

Collection<V> values() 

Set<Map.Entry<K,V>> entrySet()  

Set<K> keySet() 

import java.util.*;class MapDemo{public static void main(String[] args){Map<String,String> m = new HashMap<String,String>();m.put("1","haha1");m.put("2","haha2");m.put("3","haha3");  System.out.println(m.containsKey("1"));System.out.println(m.containsKey("11"));System.out.println(m);System.out.println(m.remove("1"));System.out.println(m);m.put("4",null);//m.put("4",null)可以使用 null 值和 null 键System.out.println(m);System.out.println(m.values());}}


Map集合的两种取出方式

1.keySet  Set<k>Map中所有的键存入到Set集合中,因为Set具备迭代器

所以可以迭代方式取出所有键,再根据get方法,获取每一个键的对应值

import java.util.*;class MapDemo{public static void main(String[] args){Map<String,String> m = new HashMap<String,String>();m.put("1","haha1");m.put("2","haha2");m.put("3","haha3");  System.out.println(m.containsKey("1"));System.out.println(m.containsKey("11"));System.out.println(m);System.out.println(m.remove("1"));System.out.println(m);m.put("4",null);//m.put("4",null)可以使用 null 值和 null 键System.out.println(m);System.out.println(m.values());}}

2.entrySet  Set<Map.Entry<kK,V>> 

Map集合中的映射关系存入到set结合中,而这个关系的数据类型就是Map.Entry

Set<Map.Entry<String,String>> entryset = m.entrySet();Iterator<Map.Entry<String,String>> it = entryset.iterator();while(it.hasNext()){Map.Entry<String,String> me = it.next();String key = me.getKey();String value = me.getValue();System.out.println(key+"="+value);}System.out.println(m.entrySet());

练习:每一个学生都有对应的归属地,学生Studdent 地址 String,学生属性:姓名,年龄

注意:姓名和年龄相同视为同一个学生,保证学生的唯一性,对学生对象的名称进行排序

1.描述学生

2.定义Map容器,将学生作为键,地址作为值,存入

3.获取Map中的元素

4.要对学生进行排序,所以要使用可以排序的TreeMap集合

import java.util.*;class MapTest{public static void main(String[ ]args){TreeMap<Student,String> tm = new TreeMap<Student,String>(new StuComparator());tm.put(new Student("zhansan",1),"BJ");tm.put(new Student("lisi",1),"TJ");tm.put(new Student("lisi6",11),"BJ");tm.put(new Student("jdsd",2),"SH");tm.put(new Student("trc",3),"GZ");tm.put(new Student("wqqy",4),"SZ");System.out.println(tm);//第一种取出方式keySetSet<Student> keyset = tm.keySet();Iterator<Student> it = keyset.iterator();while(it.hasNext()){Student stu = it.next();String addr = tm.get(stu);System.out.println(stu+"="+addr);}System.out.println();//第二种取出方式 entrySetSet<Map.Entry<Student,String>> entryset = tm.entrySet();Iterator<Map.Entry<Student,String>> it1 = entryset.iterator();while(it1.hasNext()){Map.Entry<Student,String> me = it1.next();Student stu = me.getKey();String addr = me.getValue();System.out.println(stu+"=="+addr);}}}class Student implements Comparable<Student>{private String name;private int age;Student(String name,int age){this.name = name;this.age = age;}public String getName(){return name;}public int getAge(){return age;}public int hashCode(){return name.hashCode()+age*2;}public boolean equals(Object obj){if(!(obj instanceof Student))throw new ClassCastException("类型不匹配");Student s = (Student)obj;return this.name.equals(s.name) && this.age==s.age;}public int compareTo(Student s ){int num = new Integer(this.age).compareTo(new Integer(s.age));if(num==0)return this.name.compareTo(s.name);return num;}public String toString(){return "("+name+"+"+age+")";}}class StuComparator implements Comparator<Student>{public int compare(Student s1,Student s2){int num = s1.getName().compareTo(s2.getName());if (num==0)return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));return num;}}



0 0
原创粉丝点击