JAVA-集合

集合类的特点:提供一种存储空间可变的存储模型,存储的数据容量可以随时发生改变。并且都是接口不可以创建对象,需要使用具体的实现类。

Collection集合

Collection集合在java.util下, Collection是单列集合的顶层接口,它表示一组对象,这些对象也称为Collection的元素。
JDK不提供此接口的任何直接实现,它提供更具体的子接口(List、Set)的实现

  • 创建Collection集合的对象
    多态实现;
    具体的实现类ArrayList;

  • Collection集合常用的方法
    boolean add(E e); //添加元素,无论添加什么都为true
    boolean remove(Object o); //从集合中移除指定元素
    void clear(); // 清空集合中的元素
    boolean contains(Object o); //判断集合是否存在指定元素
    boolean isEmpty(); //判断集合是否为空
    int size(); //集合的长度,即及合作中元素的个数

  • Collection 集合的遍历
    Iterator:迭代器,集合专用的遍历方式,在java.util下,Iterator<E>的泛型与集合的泛型一致。
    常用的方法:
    next(); //返回迭代中的下一个元素
    hasNext(); //如果迭代中有元素返回true,没有元素返回false
    Iterator iterator():返回此集合中元素的迭代器,通过集合的iterator()得到
    迭代器通过集合对象获取迭代器对象,所以它依赖于集合而存在。

/*
Collection集合储存学生对象并遍历
需求:创建一个存储学生对象的集合,存储3个学生对象,
使用程序实现在控制台遍历该集合
思路:
1. 定义学生类
2. 创建集合对象
3. 创建学生对象
4. 储存3个学生对象
5. 遍历集合(迭代器)
 */

    public static void main(String[] args) {
        //2. 创建一个集合对象储存学生对象
        Collection<gather.collection.Student> c = new ArrayList<gather.collection.Student>();
        //3. 创建学生对象
        gather.collection.Student student1 = new gather.collection.Student("刘备", 50);
        gather.collection.Student student2 = new gather.collection.Student("曹操",55);
        gather.collection.Student student3 = new gather.collection.Student("诸葛亮",30);
        //4. 储存3个学生对象
        c.add(student1);
        c.add(student2);
        c.add(student3);
        //5. 遍历
        Iterator<gather.collection.Student> iterator = c.iterator();
        while(iterator.hasNext()){
            Student s = iterator.next();
            System.out.println(s.getName()+":"+s.getAge());
        }
    }

Student类

public class Student {
    private String name;
    private int age;

    public Student() {//无参构造
    }

    public Student(String name, int age) {//有参构造
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

List集合

List集合在java.util下,是一个接口,继承Collection,List的泛型是List集合中元素的类型。
List为有序集合(序列),该界面的用户可以精确控制列表中每个元素的插入位置,用户可以通过整数索引(列表中的位置,从0开始)访问元素,并搜索列表中的元素。
与Set不同,List允许有重复的元素。

List集合特点

有序:存储和去除的元素一致;
重复:存储的元素可以重复。

List特有的方法

void add(int index, E element); //在此集合中特定位置插入指定元素
E remove(int index); //删除指定索引处的元素,返回被删除的元素
E set(int index, E element); //修改指定索引处的元素,返回被修改的之前的元素
E get(int index); //返回指定索引处的元素

并发修改异常

异常ConcurrentModificationException,产生的原因:迭代器遍历的过程中,通过集合对象修改了集合中的元素的长度,造成了迭代器获取元素中判断预期修改修改值和实际修改值不一致。
解决方法:用for循环遍历,

/*需求:
我有一个集合:List<String> list = new ArrayList<String>();
里面有三个元素:list.add("hello");list.add("world");list.add("Java");
遍历集合,得到每一个元素,看有没有“world”这个元素,如果有,就添加一个“javaee”元素
 * */
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("hello");
        list.add("world");
        list.add("Java");
        System.out.println(list);
        //遍历集合,得到每一个元素,看有没有“world”这个元素,如果有,就添加一个“javaee”元素
        Iterator<String> iterator = list.iterator();
        while(iterator.hasNext()){
            String s = iterator.next();
            if(s.equals("world")){

                //list.add("javaee");//异常ConcurrentModificationException
                }
        }
        //使用for循环不会出现异常ConcurrentModificationException
        for (int i = 0; i < list.size(); i++) {
            String s = list.get(i);
            if(s.equals("world")){
                list.add("javaee");
            }
        }
        System.out.println(list);
    }

List Iterator (列表迭代器)

通过List集合的listIterator()方法得到,它是 List集合特有的迭代器,在java.util下,是一个接口,继承Iterator()。
用于允许程序员沿任一方向遍历列表的列表迭代器,在迭代期间修改列表,并获取列表中迭代器的当前位置。

  • ListIterator常用方法
    E next(); //返回迭代的下一个元素
    boolean hasNext(); //有元素,返回true;没有返回false
    E previous(); //返回迭代的上一个元素
    boolean hasPrevious(); //有元素,返回true;没有返回false
    void add(E e); //将指定元素插入列表,插在了指着的位置
 public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        //添加元素
        list.add("hello");
        list.add("world");
        list.add("Java");
        //listIterator是通过List集合的listIterator()得到的
        ListIterator<String> slist = list.listIterator();

        //E next();返回迭代的下一个元素
        //boolean hasNext();有元素,返回true;没有返回false.
        while(slist.hasNext()){
            System.out.println(slist.next());
        }
        System.out.println("--------");
        //E previous();返回迭代的上一个元素
        //boolean hasPrevious();有元素,返回true;没有返回false.
        while(slist.hasPrevious()){
            System.out.println(slist.previous());
        }
        //void add(E e);将指定元素插入列表,插在了指着的位置
        slist.add("hehe");
        System.out.println(list);//[hehe, hello, world, Java]

        while (slist.hasNext()){
            String s = slist.next();
            if(s.equals("world")){
                slist.add("javaee");
            }
        }
        System.out.println(list);//[hehe, hello, world, javaee, Java]
    }

增强for循环

简化数组和Collection集合的遍历;
实现Iterator接口的类允许其对象成为增强for循环语句的目标;
JDK5之后出现的,其内部原理是一个迭代器;

		for(元素数据类型 变量名 : 数组或者Collection集合){
            if(s3.equals("world")){
                //循环体
            }
        }

List集合子类的特点

List集合常用的子类:
ArrayList:底层数据结构为数组;
LinkedList:底层数据结构为链表;

LinkedList集合特有的方法

public void addFirst(E e); //在此列表的开头插入指定元素
public void addLast(E e); //在此列表的结尾插入指定元素
public E getFirst(); //返回此列表的开头第一个元素
public E getLast(); //返回此列表的最后一个元素
public E removeFirst(); //从此列表删除并返回第一个元素
public E getLast(); //从此列表删除并返回最后一个元素

数据结构

数据结构是计算机存储、组织数据的方式,是指相互之间存在一种或多种特定关系的数据元素的集合。通常情况下,精心选择的数据结构可以带来更高的运行或存储效率。
常见的数据结构:

  • 栈:一种数据先进后出模型;
  • 队列:一种数据先进先出模型;
  • 数组:是一种查询快、增删慢的模型;索引从0开始。
    查询数据通过索引定位,查询任意数据耗时时间,速度快。
    删除数据,要将原始数据删除,同时后面每个数据前移,删除效率低。
    添加数据,添加位置后的每个数据后移,再添加数据,添加效率极低。
  • 链表:与数组对比是增删快、查询慢的模型。查询从头开始。

Set集合

set集合的特点

set集合不包括重复的元素,没有带索引的方法,所以不能使用普通for循环遍历。
set的实现类:HashSet(对集合的迭代顺序不做任何保证)、TreeSet。

HashSet

  • 哈希值:是JDK根据对象的地址或字符串或数字算出来的int类型的数值。
    Object类中有一个方法可以获得哈希值:public int hasCode();//返回对象的哈希码值。
    哈希值的特点:同一个对象多次调用hasCode()方法返回的哈希值相同,默认,不同的对象的哈希值不同,但重写hasCode()方法可以实现不同的对象的哈希值相同。
  • HashSet集合概述和特点:
    HashSet集合在java.util下,是一个具体的类,继承AbstractSet,实现Set接口。
    特点:底层数据是哈希表;对集合迭代顺序不做任何保证:不保证存储和取出元素顺序一致;没有索引,所以不能使用普通for循环遍历;由于是set集合,所以是不包括重复元素的集合。
    HashSet集合存储元素:要保证元素唯一性,需重写hashCOde()和equals()
  • 哈希表
    在JDK8之前,底层采用数组+链表实现,是一个元素为链表的数组(0-15);在JDK8之后,在长度较长的时候,底层实现了优化。
    存储数据,保证数据唯一性:哈希值%16结果为i,先与已有的数组i内数比较哈希值,再比较内容。
  • LinkedHashSet集合
    LinkedHashSet集合在java.util下,是一个具体的类,继承HashSet,实现Set接口。
    特点:哈希表和链表实现的Set接口,具有可预测的迭代顺序;由链表保证元素有序,即元素的存储和取出顺序一致;由哈希表保证元素唯一,既无重复的元素。

/*需求:创建一个储存学生对象的集合,存储多个学生对象,使用程序实现在控制台遍历该集合
  要求:学生对象的成员变量值相同,我们就认为是同一个对象
  (需要在Student类重写hashCode()和equals()----自动生成)
  思路:
  1.定义学生类
  2.创建HashSet集合对象
  3.创建学生对象
  4.把学生添加到集合
  5.遍历集合(增强for)
* */
    public static void main(String[] args) {
        //2
        HashSet<Student> hs = new HashSet<Student>();
        //3
        Student student1 = new Student("aa",16);
        Student student2 = new Student("xm",15);
        Student student3 = new Student("tx",14);
        Student student4 = new Student("ll",15);
        Student student5 = new Student("zr",13);
        Student student6 = new Student("zr",13);
        //4
        hs.add(student1);
        hs.add(student2);
        hs.add(student3);
        hs.add(student4);
        hs.add(student5);
        hs.add(student6);
        //5
        for (Student s : hs) {

            System.out.println(s.getName()+":"+s.getAge());
        }
    }

Student类重写hashCode()和equals(),保证元素唯一性

@Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age && Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

TreeSet集合

  • 特点
    java.util下,是一个具体的类,继承AbstractSet。但没有直接实现Set接口,而是间接实现。元素有序(即按照一定的规则进行排序),具体排序方式取决于构造方法。
    没有索引,不能使用普通for循环;
    由于是Set集合,所以不包含重复元素。
  • 构造方法
    TreeSet(); //无参,根据其元素的自然排序进行
    TreeSet(Comparator comparator); //有参,根据指定的比较器进行排序
  • 自然排序Comparable的使用
    用TreeSet集合存储自定义对象,无参构造方法使用的是自然排序对其元素进行排序;
    自然排序就是让元素所属的类实现Comparable接口,并重写compareTo()
    重写方法时,一定要注意排序规则必须按照要求的主要条件和次要条件进行实现。
  • 比较器排序Comparator的使用
    用TreeSet集合存储自定义对象,带参构造方法使用的是比较器排序对元素进行排序0。
    比较器排序:让集合构造方法接收Comparator的实现类对象,重写compare()方法;
    重写方法时,一定要注意排序规则必须按照要求的主要条件和次要条件进行实现。

自然排序Comparable

/*自然排序Comparable的使用
  存储学生对象并遍历,创建TreeSet集合使用无参构造方法
  要求:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序进行排序
**Comparable接口对实现它的每个类的对象强加一个整体排序(自然排序)
**所以Student类需要implements Comparable<E>并且重写compareTo()
 */
    public static void main(String[] args) {
        //创建集合对象,无参
        TreeSet<gather.collection.Student> lhs = new TreeSet<gather.collection.Student>();
        //创建学生对象
        gather.collection.Student student1 = new gather.collection.Student("aa", 10);
        gather.collection.Student student2 = new gather.collection.Student("bb", 8);
        gather.collection.Student student3 = new gather.collection.Student("dd", 12);
        gather.collection.Student student4 = new gather.collection.Student("rr", 11);
        gather.collection.Student student5 = new gather.collection.Student("zz", 12);
        //储存学生对象
        lhs.add(student1);
        lhs.add(student2);
        lhs.add(student3);
        lhs.add(student4);
        lhs.add(student5);
        //遍历
        for (Student s : lhs) {
            System.out.println(s.getName() + ":" + s.getAge());
        }
    }

Student类实现Comparable接口,并重写compareTo()

public class Student implements Comparable<Student>{
@Override
    	public int compareTo(Student s) {
//        return 0;//元素是重复的-->返回一个
//        return 1;//x2元素比x1大-->按照存储顺序输出(升序)
//        return -1;//x2元素比x1小-->按照存储顺序反序输出
        //方法内部存在this.age
        int num = this.age - s.age;//升序
//        int num = this.age - s.age;//降序
        //当年龄相同毕竟姓名,不同返回年龄差
        int num1 = num == 0 ? this.name.compareTo(s.name) : num;
        return num1;

    }
}

比较器排序Comparator

public static void main(String[] args) {
        //创建集合对象(有参构造:指定比较器的方式,接口的实现对象)
        TreeSet<gather.collection.Student> ts = new TreeSet<gather.collection.Student>(new Comparator<gather.collection.Student>() {
            @Override
            public int compare(gather.collection.Student s1, gather.collection.Student s2) {
                //自然排序:this.age-s.sge
                //比较器s1=this,s2=s
                int num1 = s1.getAge()-s2.getAge();
                int num2 = num1 == 0 ? s1.getName().compareTo(s2.getName()) : num1;
                return num2;
            }
        });

        //创建学生对象
        gather.collection.Student student1 = new gather.collection.Student("aa", 10);
        gather.collection.Student student2 = new gather.collection.Student("bb", 8);
        gather.collection.Student student3 = new gather.collection.Student("dd", 12);
        gather.collection.Student student4 = new gather.collection.Student("rr", 11);
        gather.collection.Student student5 = new gather.collection.Student("zz", 12);
        //储存学生对象
        ts.add(student1);
        ts.add(student2);
        ts.add(student3);
        ts.add(student4);
        ts.add(student5);
        //遍历
        for (Student s : ts) {
            System.out.println(s.getName() + ":" + s.getAge());
        }
    }

泛型

概述

泛型:JDK5中引入的特性,提供了编译时类型安全检测机制,它的本质是参数化类型,就是将类型由原来的具体的类型参数化,然后在使用/调用时传入具体的类型。这种参数类型可以用在类、方法和接口中,分别被称为泛型类、泛型方法和泛型接口。

泛型的定义格式

<类型>:指定一种类型的格式,类型可以看作是形参。
<类型1,类型2,…>:指定多种类型的格式,多种类型之间用逗号隔开,类型可以看作是形参。
将来具体调用时候给定的类型可以看作是实参,并且实参的类型只能是数据类型。

泛型的优点

把运行期间的问题提前到了编译期间;
避免了强制类型转换。

  • 泛型类:public class 类名{ }
  • 泛型方法:修饰符<类型> 返回值类型 方法名(类型 变量名){ }
  • 泛型接口:修饰符 interface 接口名<类型>{ }
		public class Generic02 {
		    //方法名相同,形参不同--->方法重载
		    public void show(String s){
		        System.out.println(s);
		    }
		
		    public void show(Integer i){
		        System.out.println(i);
		    }
		
		    public void show(Boolean b){
		        System.out.println(b);
		    }
		}
		//调用
		 public static void main(String[] args) {
		        //普通--方法重载
		        Generic02 g = new Generic02();
		        g.show("hhh");
		        g.show(9);
		        g.show(false);
		  }
  
		//泛型类改进
		public class Generic02<T> {
		    public void show(T s){
		        System.out.println(s);
		    }
		}
		//调用泛型类
        Generic02<String> sg = new Generic02<String>();
        sg.show("hahha");
        Generic02<Integer> ig = new Generic02<Integer>();
        ig.show(666);
        Generic02<Boolean> bg = new Generic02<Boolean>();
        bg.show(false);
        
        
		//泛型方法改进
		public class Generic02 {
	    //泛型方法
	    public<T> void show(T t){
	        System.out.println(t);
	    }
	    //调用泛型方法
	    Generic02 g = new Generic02();
	    g.show("hahah");
	    g.show(9);
	    g.show(false);

类型通配符

为了表达各种泛型List的父类,可以使用类型通配符:List<?>,表示元素类型未知的List,它的元素可以匹配任何类型。
这种通配符的List仅表示它是各种泛型List的父类,并不能把元素添加其中。

如果我们不希望List<?>是各种泛型List的父类,只希望它代表某一类泛型List的父类,可以使用类型通配符的上限:List<? extends 类型>,例如类型是Number则表示的类型是Number或其子类型。
还可以使用类型通配符的下限:List<? super 类型>,例如类型是Number则表示的类型是Number或其父类型。

	public static void main(String[] args) {
        //类型通配符:<?>
        //Object>Number>Integer
        List<?> list1 = new ArrayList<Object>();
        List<?> list2 = new ArrayList<Number>();
        List<?> list3 = new ArrayList<Integer>();
        //类型通配符的上限:<? extends Number>
        //List<? extends Number> le1 = new ArrayList<Object>();//上限为Number,报错
        List<? extends Number> le2 = new ArrayList<Number>();
        List<? extends Number> le3 = new ArrayList<Integer>();
        //类型通配符的下限:<? super Number>
        List<? super Number> ls1 = new ArrayList<Object>();
        List<? super Number> ls2 = new ArrayList<Number>();
        //List<? super Number> ls3 = new ArrayList<Integer>();//下限为Number,报错

    }

可变参数

参数的个数可变,用作方法的形参出现,所以方法的形参个数是可变的。
格式:修饰符 返回值的类型 方法名(数据类型1 , 变量名1, 数据类型2 , 变量名2,数据类型…变量名){ };
可变参数放在()的最后,变量名是一个数组。

Map集合

Map集合概述和特点

Map集合在java.util下,是一个接口,interface Map<K, V>,K是Map中的键的类型,V是值的类型。将键映射到值的对象,不能包含重复的键,每个键可以映射到最多一个值。

创建Map集合的对象

  • 多态方式;
  • 具体的实现类HashMap

Map集合的基本功能

  • public static V put(K key, V value); //添加元素,将指定的值与该映射中指定键相关联
  • V remove(Object key);//根据键删除键值对元素,返回的是V键值对中的值
  • void clear();//移除所有的键值对元素
  • boolean containsKey(Object key);//判断集合中是否含有指定的键
  • boolean containsValue(Object value);//判断集合中是否含有指定的值
  • boolean isEmpty();//判断集合是否为空
  • int size();//集合的长度,也就是集合中键值对的个数

Map集合的获取功能

  • V get(Object key);//根据键获取值
  • Set keySet();//获取所有键的集合
  • Collection values();//获取所有值的集合
  • Set<Map.Entry<K,V> entrySet();//获取所有键值对对象的集合

Map集合的遍历

  • 方式一:键找值
    Map集合中的元素都是成对出现的<key,value>
    1.获得所有键的集合
    2.增强for遍历键的Set集合,得到每个键
    3.获取每个键key对应的值value
  • 方式二:键值对象找键和值
    1.获取所有键值对对象的集合
    2.遍历键值对对象的集合,得到每个键值对对象
    3.根据键值对对象中的getKey()和getValue()分别获得键和值

集合嵌套

  1. ArrayList集合储存HashMap元素
  2. HashMap集合储存ArrayList元素

HashMap与TreeMap

  1. HashMap集合不给键做排序
  2. TreeMap集合给键做自然排序

Collections

Collections概述和特点

Collections在java.util下,是一个具体的类,继承Object,是针对集合操作的工具类。
public class Collections extends Object;

Collections类的常用方法

  • 将指定的列表按升序排序
    public static <T extends Comparable<? super T>> void sort(List list);
  • 反转指定列表中元素的顺序
    public static void reverse(List list);
  • 使用默认的随机源随机排列指定的列表
    public static void shuffle(List list);
/*案例:ArrayList存储学生对象并排序
需求:ArrayList存储学生对象,使用Collections对ArrayList进行排序
要求:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序
思路:
1.创建Student类
2.创建ArrayList集合对象
3.创建Student对象,并添加到ArrayList集合
4.使用Collections对ArrayList进行排序
5.遍历集合
* */
    public static void main(String[] args) {
        //创建集合对象
        ArrayList<Student> list = new ArrayList<Student>();
        //创建Student对象
        Student s1 = new Student(9,"aa");
        Student s2 = new Student(8,"bb");
        Student s3 = new Student(9,"dd");
        Student s4 = new Student(7,"rr");
        //添加到ArrayList集合
        list.add(s1);
        list.add(s2);
        list.add(s3);
        list.add(s4);
        //Collections.sort(list);//报错,实现对元素的自然排序,需要让元素Student类中实现自然排序接口implements
        //另一种方法:根据指定的比较器Comparator引起的顺序对指定的列表进行排序
        // public static <T> void sort(List<T> list, Comparator<? super T> c);
        Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                //按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序
                //主要条件
                int num1 = s1.getAge() - s2.getAge();
                //次要条件
                int num2 = num1==0 ? s1.getName().compareTo(s2.getName()) : num1;
                return num2;
            }
        });

        for (int i = 0; i < list.size(); i++) {
            Student s = list.get(i);
            System.out.println(s.getName() + " " + s.getAge());
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值