栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

集合框架详解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

集合框架详解

1.什么是集合

概念:对象的容器,定义了多个对多个对象进行操作的常用方法。可实现数组的功能
和数组的区别:
1.数组的长度,集合的长度不固定
2.数组可以存储基本类型和引用类型,而集合只能存储引用类型(可通过装箱基本类型来实现引用类型)

集合的位置:java.util.*

Collection体系集合

Collection父接口

特点:代表一组任意类型的对象,无序、无下标、不能重复

Collection的使用
package jihelei;

import javax.swing.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;


public class Demo01 {
    public static void main(String[] args) {
        //创建一个集合
        Collection collection =new ArrayList();//ArrayList是Collection的子类方法所以可以变相new

//        1.添加元素
        collection.add("苹果");
        collection.add("西瓜");
        collection.add("榴莲");
        System.out.println("元素个数"+collection.size());
        System.out.println(collection.toString());

//        2.删除元素
        collection.remove("榴莲");//
        System.out.println("删除之后"+collection.size());
        System.out.println(collection.toString());//toString似乎没有什么软用
        

//        3.遍历元素[重点]
        //使用增强for,普通的for循环不可以! 因为Collecting里面没有下标,所以无法通过此方法进行遍历数组
        System.out.println("============这个是第一种遍历元素的方法(增强for)==================");
        for (Object object:collection) {
            System.out.println(object);//遍历引用元素
        }

        //迭代器——专门用来遍历集合的一种方式
        

        System.out.println("=========这个是第二种遍历元素的方法(迭代器)=========================");
        Iterator iterator=collection.iterator();//迭代器(Iterator)
        while (iterator.hasNext()){
            String a=(String)iterator.next();//这里实现了一个强转换
            System.out.println(a);
            //collection.remove("西瓜");使用迭代器的时候不可以调用collection方法,否则就会出现并发修改异常
            //只能使用以下的方法
            //iterator.remove();//迭代器移除元素
        }
        System.out.println("========移除之后剩下的元素=========");
        System.out.println("剩下元素的个数:"+collection.size());


//        4.判断
        System.out.println(collection.contains("西瓜"));//判断引用数组里面有没有西瓜
        collection.isEmpty();//判断元素是不是空的
    }
}

2List接口

可实现,添加、删除、遍历、反向遍历、获取元素角标位置

List接口继承于Collection接口,因此它拥有Collection的所有方法
与Collection不一样的是,List可以设置下标添加元素
可以将一个集合添加到此集合中的某个下标位置的开始位置开始

package jihelei;

import java.sql.ClientInfoStatus;
import java.util.*;


public class Demo02List {
    public static void main(String[] args) {
        List list =new ArrayList();
        //1添加元素
        list.add(0,"苹果");
        list.add(1,"西瓜");
        list.add(2,"大蒜");
        System.out.println(list.size());
        System.out.println(list.toString());

        //2删除元素(删除之后西瓜和大蒜有新的角标,原来的作废)
        list.remove("苹果");
        System.out.println("删除之后的元素个数:"+list.size());
        System.out.println(list.toString());

        //3遍历操作
        //使用for进行遍历
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));//获取某个角标的元素
        }

        System.out.println("======增强for循环======");
        for (Object o : list) {
            System.out.println(o);
        }

        System.out.println("====迭代器输出Iterator=====");
        Iterator iterator=list.iterator();
        while (iterator.hasNext()){  //这里需要用上while循环,不可以用if,否则只有一次后面的元素输出
            String a=(String)iterator.next();//
            System.out.println(a);
        }

        //列表迭代器:可以按照任意方向进行遍历元素;比起iterator,多了一个方向遍历元素,此此外它还有添加、删除、修改元素
        System.out.println("====列表迭代器ListIterator(从前往后)======");
        ListIterator listIterator=list.listIterator();
        while (listIterator.hasNext()){
            //sout不能执行,但是soutv、soutp可以执行,一个是值的输出,一个是arg名字和值的输出
            //System.out.println("listIterator.nextIndex() + listIterator.next() = " + listIterator.nextIndex() + listIterator.next());
            System.out.println("args = " + listIterator.nextIndex() + listIterator.next());
        }

        System.out.println("====列表迭代器ListIterator(从后往前)======");
        while (listIterator.hasPrevious()){
            //sout不能执行,但是soutv、soutp可以执行,一个是值的输出,一个是arg名字和值的输出
            //System.out.println("listIterator.nextIndex() + listIterator.next() = " + listIterator.nextIndex() + listIterator.next());
            System.out.println("args = " + listIterator.previousIndex() + listIterator.previous());
        }
        System.out.print("======判断的操作=========");
        System.out.println(list.contains("苹果"));
        System.out.println(list.isEmpty());

        System.out.println("========获取位置=============");
        System.out.println(list.indexOf("大蒜"));//别的乱输入的获取位置得出的结果为-1

    }
}

3ArrayList 3.1第一部分的代码
package jihelei;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;

//ArrayList的特点:

public class Demo03ArrayList {
    public static void main(String[] args) {
        //创建集合
        ArrayList arrayList = new ArrayList<>();
        //添加元素
        System.out.println("======添加元素=============");
        Student student = new Student("随便", 15);
        Student student1 = new Student("随便1", 15);
        Student student2 = new Student("随便2", 15);
        arrayList.add(student);
        arrayList.add(student1);
        arrayList.add(student2);
        System.out.println(arrayList.size());
        System.out.println(arrayList.toString());
        //删除元素
        System.out.println("=============删除元素=============");
        arrayList.remove(student);
        System.out.println(arrayList.size());
        //遍历元素【重点】
            //使用迭代器
        System.out.println("===========迭代器遍历元素=================");
        Iterator iterator=arrayList.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        System.out.println("=====列表迭代器========");
        ListIterator listIterator=arrayList.listIterator();

        while (listIterator.hasNext()){
            System.out.println(listIterator.next());
        }
        while (listIterator.hasPrevious()){
            System.out.println(listIterator.previous());
        }
        //判断
        System.out.println("=======判断==========");
        System.out.println(arrayList.contains(student1));
        System.out.println(arrayList.contains(new Student("随便1", 15)));
        arrayList.isEmpty();

        //查找
        System.out.println("======查找位置======");
        System.out.println(arrayList.indexOf(student1));
        System.out.println(arrayList.indexOf(new Student("随便1", 15)));

    }
}

3.2第二部分的代码
package jihelei;

public class Student {
    String name;
    int age;

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + ''' +
                ", age=" + age +
                '}';
    }

    public Student(String name, int age) {
        this.name=name;
        this.age=age;

    }

    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }


    @Override
    public boolean equals(Object obj) {
        //判断是不是同一个对象
        if (this == obj) {
            return true;
        }
        //判断是不是为空
        if (obj == null) {
            return false;
        }
        //判断是不是Student类
        if (obj instanceof Student) {
            Student a =(Student)obj;
            //比较属性
            if (this.name.equals(a.getName())&&this.age==a.getAge()){
                    return true;
            }
        }
        //结果不满足
        return false;
    }
}

3.2ArrayList源码分析

ArrayList默认容量为10,在没有添加元素的情况下容量为0;
每次扩容之后容量是原来的1.5倍(这个我不知道什么意思,暂时还不知道,下次看笔记的时候再修改)

4Vector使用

特点:数组结构实现,查询快,增删慢
运行效率慢,线程安全

package jihelei;

import java.util.Enumeration;
import java.util.Vector;

//存储结构:数组
public class Demo04Vector {
    public static void main(String[] args) {
        //创建集合
        Vector objects = new Vector<>();
        //添加元素
        objects.add("苹果");
        objects.add("西瓜");
        objects.add("葡萄");
        System.out.println(objects.size());
        //删除元素
        // objects.remove(0);
         objects.remove("西瓜");
        // objects.clear();
         //遍历元素


            //使用枚举器*********
        Enumeration elements = objects.elements();//element是元素的意思,Vector含有element方法


        while (elements.hasMoreElements()){
           String a=(String) elements.nextElement();//强制转换
            System.out.println(a);
        }
        //判断
        System.out.println(objects.isEmpty());
        System.out.println(objects.contains("葡萄"));
        //Vector的其他方法
        System.out.println(objects.firstElement());
        System.out.println(objects.lastElement());


    }
}

 
5泛型 
泛型类 
package jihelei;

public class Demo06GenericTest {
        //使用泛型
        //创建变量
        T t;
        //泛型作为方法的参数
        public void show(T t){
            //不能new T,也就是不能实例化泛型
            System.out.println(t);
        }

        //泛型作为方法的返回值
        public T getT(){
            return t;
        }


  public static  void main(String[] args) {
        //使用泛型类来创建对象
        Demo06GenericTest a1 = new Demo06GenericTest();
        a1.t="hello";
        a1.show("大家好");
        System.out.println(a1.getT());

        Demo06GenericTest a2 = new Demo06GenericTest();
        a2.t=10;
        a2.show(20);
        System.out.println(a2.getT());
    }
}

泛型接口
package jihelei;

public interface Demo07MyInterface{
    String name="张三";
    T service(T t);
}

<类型> 中间定义了什么类型,那么方法中中的形参也就是什么类型

package jihelei;

public class Demo08MyInterfaceImpl implements Demo07MyInterface{


    @Override
    public String service(String s) {
        System.out.println(s);
        return s;
    }
}

package jihelei;

public class Demo08MyInterfaceImpl implements Demo07MyInterface{


    @Override
    public Integer service(Integer integer) {
        System.out.println(integer);
        return integer;
    }
}

只要实例化调用方法,输入什么类型就是什么类型,不用特意的对应。

package jihelei;

public class Demo09MyInterfaceImpl2 implements Demo07MyInterface{
    @Override
    public T service(T t) {
        System.out.println(t);
        return t;

    }
}

泛型方法
package jihelei;

public class MyGenericMethod {
    public void haha(T t){
        System.out.println("泛型方法"+t);
    }
}

然后随便用一个类调用一下就可以得出以下的这些结果了

 public static void main(String[] args) {
        MyGenericMethod myGenericMethod = new MyGenericMethod();
        myGenericMethod.haha("中国加油");
        myGenericMethod.haha(10);
        myGenericMethod.haha(3.14);
    }
泛型集合

说实话我自己这个也不是很明白到底老师为什么这么讲的,不是很理解,但是这个肯定是个好东西就是了,sorry

package jihelei;

import java.util.ArrayList;
import java.util.Iterator;

public class Demo11 {
    public static void main(String[] args) {
        ArrayList a = new ArrayList();
        a.add("");
        a.add("");

        for (String s : a) {
            System.out.println(s);
        }

        ArrayList a1 = new ArrayList();
        Student student = new Student("刘德华", 15);
        Student student1 = new Student("刘德华", 15);
        Student student2 = new Student("刘德华", 15);

        a1.add(student);
        a1.add(student1);
        a1.add(student2);

        Iterator iterator = a1.iterator();
        while (iterator.hasNext()){
            Student s=iterator.next();
            System.out.println(s.toString());
        }
    }
}

总结泛型的特点

好处:
1.提高代码的重用性
2.防止类型准换异常,提高代码的安全性

6Set
package jihelei;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;


public class Demo12 {
    public static void main(String[] args) {
        //创建一个集合
        Set set = new HashSet<>();
        set.add("苹果");
        set.add("香蕉");
        set.add("西瓜");
        set.add("西瓜");//重复的不显示
        System.out.println(set.size());
        System.out.println(set.toString());

        //删除数据
        set.remove("西瓜");//即使是前面有一个重复的,删除之后依旧是删除掉所有这个相关字符串的内容
        System.out.println(set.toString());

        //遍历1.增强for循环2.使用迭代器、
        for (String s : set) {
            System.out.println(s.toString());
        }
        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        //判断
        System.out.println(set.contains("西瓜"));
        System.out.println(set.isEmpty());
    }
}


6.1Set实现类(HashSet)
package jihelei;

import java.util.HashSet;
import java.util.Iterator;


public class Demo13 {
    public static void main(String[] args) {
        //新建集合
        HashSet  ha = new HashSet();
        //添加元素
        ha.add("1");
        ha.add("2");
        ha.add("3");
        ha.add("4");
        System.out.println(ha.size());
        System.out.println(ha.toString());
        //删除数据
        ha.remove("1");
        System.out.println(ha.toString());
        //遍历:增强for、迭代器、
        for (String s : ha) {
            System.out.println(s);
        }
        Iterator iterator = ha.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        //判断
        ha.contains("5");
        ha.isEmpty();
    }
}

6.2HashSet存储方式
package jihelei;

import java.util.HashSet;
import java.util.Objects;


public class Demo14 {
    private int age;
    private String name;
    public Demo14(String name,int age) {
        this.name=name;
        this.age=age;
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }


    @Override
    public String toString() {
        return "Demo14{" +
                "age=" + age +
                ", name='" + name + ''' +
                '}';
    }

    @Override
    public int hashCode() {
        int n1=this.name.hashCode();
        int n2=this.age;
        return n1+n2;

    }

    @Override
    public boolean equals(Object o) {
        if (this==o){
            return true;
        }
        if (o==null){
             return false;
        }
        if (o instanceof Demo14){
            Demo14 a=(Demo14)o;
            if (this.name.equals(a.getName())&&this.age==a.getAge()){
                return true;
            }
        }
       return false;
    }

    public static void main(String[] args) {
        //创建集合
        HashSet demo14 = new HashSet<>();
        //添加数据
        Demo14 name1 = new Demo14("名字1", 10);
        Demo14 name2 = new Demo14("名字2", 11);
        Demo14 name3 = new Demo14("名字3", 12);
        Demo14 name4 = new Demo14("名字4", 13);

        demo14.add(name1);
        demo14.add(name2);
        demo14.add(name3);
        demo14.add(name4);
        demo14.add(name4);
        demo14.add(new Demo14("名字4", 13));

        System.out.println(demo14.size());
        System.out.println(demo14.toString());
        //删除操作
        demo14.remove(new Demo14("名字1", 10));//重写了hashCode方法之后就可以删除,但是没有重写之前不可以删除掉

        //遍历:增强for,迭代器,同上
        //判断
        System.out.println(demo14.contains(new Demo14("名字2", 11)));//重写了equals和hashcode方法,于是乎就是对的
        demo14.isEmpty();


    }
}

6.3HashSet补充

HashSet有一个质数31

6.4TreeSet使用

这里先创建一个类,随便叫什么都可以

package jihelei;

public class Student implements Comparable {//
    String name;
    int age;

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + ''' +
                ", age=" + age +
                '}';
    }

    public Student(String name, int age) {
        this.name=name;
        this.age=age;

    }

    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }




   //TreeSet,
    @Override
    public int compareTo(Student o) {
        int n1=this.getName().compareTo(o.getName());
        int n2=this.getAge()-o.getAge();

        return n1==0?n1:n2;//先按照年龄比较,再按照姓名比较,大小按照:a-z// ,1-++++数字,小的选出来

    }
}

然后创建集TreeSet类

package jihelei;

import java.util.TreeSet;


public class TreeSetDemo16 {
    public static void main(String[] args) {
        //创建一个集合
        TreeSet treeSet = new TreeSet<>();

        Student student1 = new Student("xyz", 11);
        Student student2 = new Student("hwbjh", 10);
        Student student3 = new Student("suibian", 12);
        Student student4 = new Student("yhangsan", 12);
        //Student student5 = new Student("yhangsan", 12);


        treeSet.add(student1);
        treeSet.add(student2);
        treeSet.add(student3);
        treeSet.add(student4);
        //treeSet.add(student5);

        System.out.println(treeSet.size());
        System.out.println(treeSet.toString());

        //删除(同上)
        //treeSet.remove(student1);
        //遍历:增强for、迭代器(同上)
        //判断
        System.out.println(treeSet.contains(new Student("xyz", 11)));


    }
}

6.5Comparator接口(字符串、数字的排序)
 package jihelei;

import java.util.Comparator;
import java.util.TreeSet;


public class TreeSetDemo17 {
    public static void main(String[] args) {
        //创建集合,并指定比较规则
        TreeSet students = new TreeSet<>(new Comparator() {
            @Override
            public int compare(Student o1, Student o2) {
                int n1= o1.getAge()-o2.getAge();
                int n2=o1.getName().compareTo(o2.getName());
                return n1==0?n2:n1;

            }
        });

        Student student1 = new Student("xyz", 11);
        Student student2 = new Student("hwbjh", 10);
        Student student3 = new Student("suibian", 12);
        Student student4 = new Student("yhangsan", 12);

        students.add(student1);
        students.add(student2);
        students.add(student3);
        students.add(student4);

        System.out.println(students.toString());
    }
}

6.6TreeSet案例(字符串长度的排序)
package jihelei;

import java.util.Comparator;
import java.util.TreeSet;


public class TreeSetDemo18 {
    public static void main(String[] args) {
        //创建集合,并且指定比较规则
        TreeSet strings = new TreeSet<>(new Comparator() {
            @Override
            public int compare(String o1, String o2) {
                int n1=o1.length()-o2.length();
              //  int n2=o1.compareTo(o2);

                return n1;//==0?n2:n1
            }
        });

        //添加数据
        strings.add("bhjkgjk");
        strings.add("njk");
        strings.add("bnjk");
        strings.add("bkhjbjyh");
        strings.add("bhjfwjhbfw");
        strings.add("bhjfwjhbfw");

        System.out.println(strings.toString());


    }
}

10Map接口的使用 10.1map.keySetmap.entrySet




package jihelei;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;


public class Demo19Map {
    public static void main(String[] args) {
        //创建Map集合
        Map map=new HashMap<>();
        //添加元素
        map.put("a","中国1");
        map.put("b","中国2");
        map.put("c","中国3");
        //map.put("c","中国4");//当后面添加重复的key的时候就会把前面的覆盖掉

        System.out.println(map.toString());

        //删除元素(直接删除key就可以)
        map.remove("a");

        //3.遍历:  1.keySet方法 2.entrySet方法
        Set set = map.keySet();
        for (String s : set) {
            System.out.println(s+" "+map.get(s));
        }

        Set> entries = map.entrySet();
        for (Map.Entry entry : entries) {
            System.out.println(entry.getKey()+" "+entry.getValue());

        }

        //判断
        map.containsKey("a");
        map.containsValue("中国1");
    }
}

10.2HashMap使用

HashMap允许用null作为key或者value

package jihelei;

import java.security.spec.RSAOtherPrimeInfo;
import java.util.HashMap;
import java.util.Map;


public class Demo20HashMap {
    public static void main(String[] args) {
        //创建元素
        HashMap hashMap = new HashMap<>();
        //添加元素
        Student student1 = new Student("名字1",10);
        Student student2 = new Student("名字2",11);
        Student student3 = new Student("名字3",12);

        hashMap.put(student1,"老大");
        hashMap.put(student2,"老二");
        hashMap.put(student3,"老三");
           // hashMap.put(student3,"老四");//如果添加新的value,就会把之前的key关于Student的给覆盖掉
          
        hashMap.put(new Student("名字1",10),"老大2");


        System.out.println(hashMap.size());
        System.out.println(hashMap.toString());

        //删除元素
        hashMap.remove(student1);
        System.out.println(hashMap.toString());

        //遍历:1.使用keySet,2.entrySet
       for (Student key:hashMap.keySet()){
           System.out.println(key.toString()+" "+hashMap.get(key));
       }
      for (Map.Entry entry:hashMap.entrySet()){
          System.out.println(entry.getKey()+" "+entry.getValue());
      }
        //判断
        System.out.println(hashMap.containsKey(student2));
        System.out.println(hashMap.containsValue("老二"));


    }
}

10.3HashMap源码分析 HashMap和Propeties

HashMap允许key和value为空
但是 HashTable不允许
Properties继承于HashTable

package jihelei;

import java.util.Map;
import java.util.TreeMap;

public class Demo21TreeMap {
    public static void main(String[] args) {
        TreeMap treeMap = new TreeMap<>();//这边可以 new TreeMap<>(new Comparable){}进行定制比较
        //添加元素
        Student student1 = new Student("名字1",10);
        Student student2 = new Student("名字2",11);
        Student student3 = new Student("名字3",12);
        //这里面的意思就是放一个Student类型标签、外加一个字符串内容
        treeMap.put(student1,"diyi");
        treeMap.put(student2,"dier");
        treeMap.put(student3,"disan");
        System.out.println(treeMap.size());
        System.out.println(treeMap.toString());//要先实现Student继承Comparable,重写hashcode方法


        //删除元素
        treeMap.remove(student1);


        //遍历元素
        for (Student key:treeMap.keySet()){
            System.out.println(key+" "+treeMap.keySet());
        }
        //把entry当作是票、entryset就是先设置票出来才能访问(造票)、treeMap.entrySet()地图造票、key就是票的代号、value就是票面信息
        for (Map.Entry entry:treeMap.entrySet()){
            System.out.println(entry.getKey()+" "+entry.getValue());
        }
        //
    }
}

11Collections工具类
package jihelei;

import java.util.*;


public class Demo22Collection {
    public static void main(String[] args) {
       List arrayList = new ArrayList<>();
       arrayList.add(1);
       arrayList.add(2);
       arrayList.add(3);



       //给数字进行排序
       Collections.sort(arrayList);//默认从小到大
        System.out.println(arrayList.toString());



        //查找所需要的数字:二分查找
        System.out.println(Collections.binarySearch(arrayList, 3));



        //copy复制
        ArrayList arrayList1 = new ArrayList<>();
        for (Integer integer : arrayList) {
            arrayList1.add(0);
        }
        Collections.copy(arrayList1,arrayList);//复制要实现大小一致,因为新创建的arrayList1大小为0,需要实现上面一步骤的操作
        System.out.println(arrayList1.toString());


        //reverse反转
        Collections.reverse(arrayList);
        System.out.println(arrayList.toString());

        //shuffle打乱
        Collections.shuffle(arrayList);
        System.out.println(arrayList);

        //补充: list转成数组、数组转成list
        //集合t转成数组
        Integer[] integers = arrayList.toArray(new Integer[0]);
        System.out.println(integers.length);
        System.out.println(Arrays.toString(integers));

        //数组转成集合
            //这是一个受限制的集合,不能添加和删除元素,如果进行list.add()运行就会报错
        String[] names={"名字1","名字2","名字3"};
        List list = Arrays.asList();
        list.add("名字4");
        list.toString();
        //把基本类型数组转换成集合时需要修改为包装类
        Integer[] nums={1,2,3,4,5,};
        List list1 = Arrays.asList(nums);
        System.out.println(list1);
    }
}

总结


linkHashMap与HashMap的用法是一样的,只是linkHashMap是有序的

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号