前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java集合框架

Java集合框架

作者头像
用户7353950
发布2022-06-23 16:09:47
2.3K0
发布2022-06-23 16:09:47
举报
文章被收录于专栏:IT技术订阅IT技术订阅

1.集合和数组的区别

  • 数组长度是固定的,集合长度是可变的
  • 数组可以存储基本类型和引用类型,集合只能存储引用类型

2.Collection体系集合

List接口的特点:

有序、有下标、元素可重复

Set接口的特点:

无序、无下标、元素不能重复

2.1Collection父接口

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

方法:

  • boolean add(Object obj) //添加一个对象
  • boolean addAll(Collection c) //将一个集合中的所有对象添加到此集合中
  • void clear() //清空此集合中的所有对象
  • boolean contains(Object o) //检查此集合中是否包含o对象
  • boolean equals(Object o) //比较此集合是否与指定对象相等
  • boolean isEmpty() //判断此集合是否为空
  • boolean remove(Object o) //在此集合中移除o对象
  • int size() //返回此集合中的元素个数
  • Object[] toArray() //将此集合转换成数组

collection操作:

代码语言:javascript
复制
package com.framework.collection;

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

/*
Collection接口的使用
1。添加元素
2。删除元素
3。遍历元素
4。判断
*/
public class Demo01 {
   public static void main(String[] args) {
       //创建一个集合
       Collection collection = new ArrayList();
       //1。添加元素
       collection.add("苹果");
       collection.add("榴莲");
       collection.add("香蕉");
       System.out.println("元素个数:" + collection.size());
       System.out.println(collection);
       //2。删除元素
       collection.remove("榴莲");
       System.out.println("剩下的元素:" + collection);
       System.out.println("===========================================");
       //清空 collection.clear();
       //3。遍历元素
       //增强for循环
       for (Object object: collection) {
           System.out.println(object);
      }
       System.out.println("===========================================");
       //使用迭代器(专门用于遍历集合的方式)
       //hasNext();有没有下一个元素
       //next();获取下一个元素
       //remove();删除当前元素
       Iterator it = collection.iterator();
       while (it.hasNext()){
           String s = (String) it.next();
           System.out.println(s);
           it.remove();
      }//迭代器迭代过程中不能使用collection删除方法删除元素
       System.out.println(collection.size());
       System.out.println("===========================================");
       //4。判断
       System.out.println(collection.contains("苹果"));
       System.out.println(collection.isEmpty());
  }
}
代码语言:javascript
复制
package com.framework.collection;

import org.w3c.dom.ls.LSOutput;

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

   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;
  }

   @Override
   public String toString() {
       return "Student{" +
               "name='" + name + '\'' +
               ", age=" + age +
               '}';
  }
}
代码语言:javascript
复制
package com.framework.collection;

import java.util.ArrayList;
import java.util.Collection;

public class Demo02 {
   public static void main(String[] args) {
       //collection的使用
       //新建一个collection对象
       Collection collection = new ArrayList();
       Student s1 = new Student("zhangsan", 22);
       Student s2 = new Student("zhao", 21);
       Student s3 = new Student("wang", 20);
       //添加学生数据
       collection.add(s1);
       collection.add(s2);
       collection.add(s3);
       collection.add(s3);
       System.out.println("元素个数:" + collection.size());
       System.out.println(collection.toString());
       //删除
       collection.clear();//对象和集合都在堆中,集合中储存的是对象的地址,删除是删除集合中的地址,对象还在
       System.out.println("删除之后:" + collection.toString());
       //遍历
       //增强for
       System.out.println("==========================================");
       for (Object object: collection) {
           Student s = (Student) object;
           System.out.println(s.toString());
      }
       System.out.println("==========================================");
       //迭代器
       Iterator it = collection.iterator();
       while (it.hasNext()){
           Student s = (Student) it.next();
           System.out.println(s.toString());
      }
       //判断
       System.out.println(collection.contains(s1));
       System.out.println(collection.isEmpty());
  }
}

3.List集合

特点:有序、有下标、元素可以重复

方法:

  • void add(int index,Object o) //在index位置插入对象o
  • boolean addAll(int index,Collection c) //将一个集合中的元素添加到此集合中的index位置
  • Object get(int index) //返回集合中指定位置的元素
  • List subList(int fromIndex , int toIndex) //返回fromIndex和toIndex之间的集合元素
代码语言:javascript
复制
package com.framework.list;

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

public class Demo01 {
   public static void main(String[] args) {
       //先创建集合对象
       List list = new ArrayList();
       //添加元素
       list.add("手机");
       list.add("手表");
       list.add("电脑");
       System.out.println("元素的个数:" + list.size());
       System.out.println(list.toString());
       //删除
       //list.remove("手机");
       list.remove(0);
       System.out.println("删除之后:" + list.toString());
       //遍历
       //for
       for (int i = 0; i < list.size(); i++) {
           String s = (String) list.get(i);
           System.out.println(s);
      }
       System.out.println("=========================");
       //增强for
       for (Object o : list) {
           System.out.println(o);
      }
       System.out.println("=========================");
       //迭代器
       Iterator it = list.iterator();
       while (it.hasNext()){
           System.out.println(it.next());
      }
       System.out.println("==========================");
       //使用列表迭代器,和Iterator区别
       //listIterator可以向前或向后遍历,添加,删除,修改元素
       ListIterator lit = list.listIterator();
       System.out.println("=============使用列表迭代器从前往后=================");
       while (lit.hasNext()){
           System.out.println(lit.nextIndex() + ":" + lit.next());
      }
       System.out.println("=============使用列表迭代器从后往前=================");
       while (lit.hasPrevious()){
           System.out.println(lit.previousIndex() + ":" + lit.previous());
      }
       System.out.println("============================");
       //判断
       System.out.println(list.contains("电脑"));
       System.out.println(list.isEmpty());
       System.out.println("============================");
       //获取位置
       System.out.println(list.indexOf("手表"));
  }
}
代码语言:javascript
复制
package com.framework.list;

import java.util.ArrayList;
import java.util.List;

public class Demo02 {
   public static void main(String[] args) {
       //创建集合
       List list = new ArrayList();
       //添加数字数据(自动装箱,int变成integer)
       list.add(20);
       list.add(30);
       list.add(40);
       list.add(50);
       list.add(60);
       list.add(70);
       System.out.println("元素个数:" + list.size());
       System.out.println(list.toString());
       //删除
       list.remove((Integer)20);
       System.out.println("删除元素:" + list.size());
       System.out.println(list.toString());
       //subList方法,返回子集合,含头不含尾
       List subList = list.subList(1, 3);
       System.out.println(subList.toString());
  }
}

3.1List实现类

3.1.1ArrayList
  • 数组结构实现,查询快,增删慢
  • 运行效率快、线程不安全

ArrayList默认容量

  • DEFAULT_CAPACITY =10,默认容量为10
  • elementData存放元素的数组
  • size 实际的元素个数<=容量
  • 如果没有向集合中添加任何元素时,容量为0,添加任意一个元素之后,容量变为10,每次扩容大小是原来的1.5倍

ArrayList

代码语言:javascript
复制
package com.framework.ArrayList;

import com.framework.collection.Student;

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

public class Demo01 {
   public static void main(String[] args) {
       //创建集合
       ArrayList arrayList = new ArrayList();
       //添加
       Student s1 = new Student("刘德华",21);
       Student s2 = new Student("周杰伦",21);
       Student s3 = new Student("陈奕迅",21);
       arrayList.add(s1);
       arrayList.add(s2);
       arrayList.add(s3);
       System.out.println("元素个数:" + arrayList.size());
       System.out.println(arrayList.toString());
       //删除
       //arrayList.remove(new Student("刘德华", 21));//equals(this == obj)
       //System.out.println("删除之后:" + arrayList.toString());
       //遍历,迭代器
       System.out.println("=======================================");
       Iterator it = arrayList.iterator();
       while (it.hasNext()){
           Student s = (Student) it.next();
           System.out.println(s.toString());
      }
       System.out.println("================列表迭代器=======================");
       ListIterator lit = arrayList.listIterator();
       while (lit.hasNext()){
           Student s = (Student) lit.next();
           System.out.println(s.toString());
      }
       System.out.println("================逆序=======================");
       while (lit.hasPrevious()){
           Student s = (Student) lit.previous();
           System.out.println(s.toString());
      }
       //判断
       System.out.println("=======================================");
       System.out.println(arrayList.contains(new Student("刘德华", 21)));
       System.out.println(arrayList.isEmpty());
       //查找
       System.out.println("=======================================");
       System.out.println(arrayList.indexOf(new Student("刘德华", 21)));
  }
}

重写equals方法

代码语言:javascript
复制
@Override
   public boolean equals(Object o) {
       //判断是不是同一个对象
       if (this == o) {
           return true;
      }
       //判断是否为空
       if (o == null) {
           return false;
      }
       //判断是否是Student类型
       if (o instanceof Student){
           Student s = (Student) o;
           //比较属性
           if (this.name.equals(s.getName())&&this.age == s.getAge()){
               return true;
          }
      }
       //不满足返回false
       return false;
  }
3.1.2Vector
  • 数组结构实现,查询快,增删慢
  • 运行效率慢、线程安全
代码语言:javascript
复制
package com.framework.vector;

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

public class Demo01 {
   public static void main(String[] args) {
       //创建集合
       Vector vector = new Vector();
       //添加元素
       vector.add("草莓");
       vector.add("芒果");
       vector.add("西瓜");
       //打印
       System.out.println("元素个数:" + vector.size());
       System.out.println(vector.toString());
       //删除
//       vector.remove(0);
//       vector.remove("西瓜");
//       vector.clear();
       //使用枚举器遍历
       Enumeration elements = vector.elements();
       while (elements.hasMoreElements()){
           String s = (String) elements.nextElement();
           System.out.println(s);
      }
       //判断
       System.out.println(vector.contains("西瓜"));
       System.out.println(vector.isEmpty());
       //vector其他方法
//       vector.firstElement();
//       vector.lastElement();
//       vector.elementAt();

  }
}
3.1.3LinkedList
  • 链表结构实现,增删快,查询慢

LinkedList

  • 存储结构:双向链表
代码语言:javascript
复制
package com.framework.linkedlist;

import com.framework.collection.Student;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;

public class Demo01 {
    public static void main(String[] args) {
        //创建集合
        LinkedList linkedList = new LinkedList();
        //添加元素
        Student s1 = new Student("橘猫", 22);
        Student s2 = new Student("蓝猫", 21);
        Student s3 = new Student("大花猫", 20);

        linkedList.add(s1);
        linkedList.add(s2);
        linkedList.add(s3);

        System.out.println("元素个数:" + linkedList.size());
        System.out.println(linkedList.toString());
        //删除
        linkedList.remove(s1);
        System.out.println("删除之后:" + linkedList.size());
        System.out.println(linkedList.toString());
        //遍历
        System.out.println("=================for===================");
        for (int i = 0; i < linkedList.size(); i++) {
            System.out.println(linkedList.get(i));
        }
        System.out.println("=================增强for===================");
        for (Object o: linkedList) {
            Student s = (Student) o;
            System.out.println(s.toString());
        }
        System.out.println("=================迭代器===================");
        Iterator iterator = linkedList.iterator();
        while (iterator.hasNext()){
            Student s = (Student) iterator.next();
            System.out.println(s.toString());
        }
        System.out.println("=================list迭代器===================");
        ListIterator listIterator = linkedList.listIterator();
        while (listIterator.hasNext()){
            Student s = (Student) listIterator.next();
            System.out.println(s.toString());
        }
        //从后往前
        while (listIterator.hasPrevious()){
            Student s = (Student) listIterator.previous();
            System.out.println(s.toString());
        }
        //判断
        System.out.println(linkedList.contains(s1));
        System.out.println(linkedList.isEmpty());
        //获取
        System.out.println(linkedList.indexOf(s1));
    }
}

ArrayList和LinkedList区别:

  • ArrayList必须开辟连续空间,查询快,增删慢
  • LinkedList无需开辟连续空间,查询慢,增删快

4.泛型

常见形式有泛型类、泛型接口、泛型方法

语法:

代码语言:javascript
复制
<T,...> T称为类型占位符,表示一种引用类型

好处:

  • 提高代码的重用性
  • 防止类型转换异常,提高代码的安全性

4.1泛型类

代码语言:javascript
复制
package com.framework.MyGeneric;

//泛型类      T表示一种引用类型,如果写多个,用逗号隔开
public class MyGenericDemo01<T> {

        //使用泛型T创建变量
        T t;
        //作为方法的参数
    public void show(T t){
        //不能实例化(不能new)
        System.out.println(t);
    }
    //使用泛型作为方法的返回值
    public T getT(){
        return t;
    }

}
代码语言:javascript
复制
package com.framework.MyGeneric;

public class TestGeneric {
    public static void main(String[] args) {
        //使用泛型类创建对象
        //1。泛型只能使用引用类型
        //2。不同泛型类型对象之间不能相互赋值
        MyGenericDemo01<String > myGeneric = new MyGenericDemo01<String>();
        myGeneric.t = "hello";
        myGeneric.show("大家好");
        String t = myGeneric.getT();

        MyGenericDemo01<Integer> myGeneric2 = new MyGenericDemo01<Integer>();
        myGeneric2.t = 100;
        myGeneric2.show(200);
        Integer integer = myGeneric2.getT();
    }
}

4.2泛型接口

代码语言:javascript
复制
package com.framework.MyGeneric;

//泛型接口
public interface MyInterface<T> {
    String name = "zhangsan";

    //不能创建泛型静态常量
    T server(T t);

}
代码语言:javascript
复制
package com.framework.MyGeneric;

public class MyInterfaceImpl implements MyInterface<String> {
    @Override
    public String server(String s) {
        System.out.println(s);
        return s;
    }

}
代码语言:javascript
复制
package com.framework.MyGeneric;

public class TestGeneric {
    public static void main(String[] args) {

        MyInterfaceImpl impl = new MyInterfaceImpl();
        impl.server("xxxxx");

        MyInterfaceImpl2<Integer> impl2 = new MyInterfaceImpl2<>();
        impl2.server(1000);
    }
}

4.3泛型方法

代码语言:javascript
复制
package com.framework.MyGeneric;

//泛型方法
//语法:<T> 返回值类型
public class MyGenericMethod {
    //泛型方法
    public <T> void show(T t){
        System.out.println("泛型方法:" + t);
    }
}
代码语言:javascript
复制
package com.framework.MyGeneric;

public class TestGeneric {
    public static void main(String[] args) {
        
        //泛型方法
        MyGenericMethod myGenericMethod = new MyGenericMethod();
        myGenericMethod.show("张三");
    }
}

4.4泛型集合

概念:参数化类型、类型安全的集合,强制集合元素的类型必须一致

特点:

  • 编译时检查,而非运行时抛出异常
  • 访问时,不必类型转换
  • 不同泛型之间引用不能相互赋值,泛型不存在多态
代码语言:javascript
复制
package com.framework.MyGeneric;

import com.framework.collection.Student;

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

public class Demo01 {
    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.add("xxxx");
        arrayList.add("yyyy");
        //arrayList.add(20);
        //arrayList.add(30);
        for (String s:
             arrayList) {
            System.out.println(s);
        }

        ArrayList<Student> arrayList1 = new ArrayList<Student>();
        Student s1 = new Student("肥肥", 21);
        Student s2 = new Student("甜甜", 24);
        Student s3 = new Student("猪猪", 22);
        arrayList1.add(s1);
        arrayList1.add(s2);
        arrayList1.add(s3);
        Iterator<Student> iterator = arrayList1.iterator();
        while (iterator.hasNext()){
            Student next = iterator.next();
            System.out.println(next);
        }

    }
}

5.Set子接口

特点:无序、无下标、元素不可重复

方法:全部继承自collection中的方法

5.1Set实现类

5.1.2HashSet
  • 基于HashSet计算元素存放位置
  • 当存入元素的哈希码相同时,会调用equals进行确认,如果结果为true,则拒绝后者存入
代码语言:javascript
复制
package com.framework.set;

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

//测试Set接口的使用
public class SetInterfaceDemo01 {
    public static void main(String[] args) {
        //创建集合
        Set<String> set = new HashSet<>();
        //添加数据
        set.add("苹果");
        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.增强for2.迭代器)
        System.out.println("=====================增强for=====================");
        for (String s:
             set) {
            System.out.println(s);
        }
        System.out.println("=====================迭代器======================");
        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()){
            String next = iterator.next();
            System.out.println(next);
        }
        //判断
        System.out.println(set.contains("华为"));
        System.out.println(set.isEmpty());
    }
}
代码语言:javascript
复制
package com.framework.set;

import java.util.Objects;

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

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

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

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

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

//    @Override
//    public boolean equals(Object o) {
//        if (this == o) {
//            return true;
//        }
//        if (o == null ) {
//            return false;
//        }
//        if (o instanceof Person){
//            Person p = (Person) o;
//            if (this.name.equals(p.getName())&&this.age == p.getAge()){
//                return true;
//            }
//        }
//        return false;
//    }
//
//    @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 || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age && Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}
代码语言:javascript
复制
package com.framework.set;

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

/*存储过程:
1.根据hashcode计算保存的位置,如果此位置为空,则直接保存,如果不为空执行第二步
2.再执行equals方法,如果equals方法为true,则认为是重复,否则,形成链表
 */

public class Demo03 {
    public static void main(String[] args) {
        //新建集合
        HashSet<Person> person = new HashSet<>();
        Person p1 = new Person("肥肥", 21);
        Person p2 = new Person("猪猪", 24);
        Person p3 = new Person("侠侠", 23);
        Person p4 = new Person("甜甜", 22);
        person.add(p1);
        person.add(p2);
        person.add(p3);
        person.add(p4);
        person.add(new Person("甜甜", 22));
        System.out.println("元素个数:" + person.size());
        System.out.println(person.toString());
        //删除
        //System.out.println(person.remove(new Person("侠侠", 23)));
        //System.out.println(person.remove(p3));
        //遍历
        System.out.println("====================增强for====================");
        for (Person p:
             person) {
            System.out.println(p);
        }
        System.out.println("====================迭代器====================");
        Iterator<Person> iterator = person.iterator();
        while (iterator.hasNext()){
            Person next = iterator.next();
            System.out.println(next);
        }
        //判断
        System.out.println(person.contains(p1));
        System.out.println(person.contains(new Person("侠侠", 23)));
    }
}
5.1.3TreeSet
  • 基于排列顺序实现元素不重复
  • 实现了SortedSet接口,对集合元素的自动排序
  • 元素对象的类型必须实现Comparable接口,指定排序规则
  • 通过ComparaTo方法确定是否为重复元素
代码语言:javascript
复制
package com.framework.set.treeset;

import java.util.Iterator;
import java.util.TreeSet;

//存储结构:红黑树
public class Demo01 {
    public static void main(String[] args) {
        //创建集合
        TreeSet<String> treeSet = new TreeSet<>();
        //添加元素
        treeSet.add("ddd");
        treeSet.add("aaa");
        treeSet.add("ccc");
        treeSet.add("bbb");
        treeSet.add("bbb");
        System.out.println("元素个数:" + treeSet.size());
        System.out.println(treeSet.toString());
        //删除
        treeSet.remove("aaa");
        System.out.println(treeSet.toString());
        //遍历
        System.out.println("====================增强for===================");
        for (String s: treeSet) {
            System.out.println(s);
        }
        System.out.println("====================迭代器===================");
        Iterator<String> iterator = treeSet.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        //判断
        System.out.println(treeSet.contains("aaa"));
    }
}
代码语言:javascript
复制
package com.framework.set.treeset;

import java.util.Objects;

public class Person implements Comparable<Person>{
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

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

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

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

//    @Override
//    public boolean equals(Object o) {
//        if (this == o) {
//            return true;
//        }
//        if (o == null ) {
//            return false;
//        }
//        if (o instanceof Person){
//            Person p = (Person) o;
//            if (this.name.equals(p.getName())&&this.age == p.getAge()){
//                return true;
//            }
//        }
//        return false;
//    }
//
//    @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 || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age && Objects.equals(name, person.name);
    }

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

    //先比姓名,再比年龄
    @Override
    public int compareTo(Person o) {
        int n1 = this.getName().compareTo(o.getName());
        int n2 = this.age - o.getAge();
        return n1==0?n2:n1;
    }
}
代码语言:javascript
复制
package com.framework.set.treeset;

import com.framework.set.treeset.Person;

import java.util.Iterator;
import java.util.TreeSet;

/*
使用TreeSet保存数据

要求:元素必须要实现Comparable接口,comparaTo()方法返回值为0,认为是重复元素
 */
public class Demo02 {
    public static void main(String[] args) {
        //创建集合
        TreeSet<Person> person = new TreeSet<>();
        Person p1 = new Person("bbb", 21);
        Person p2 = new Person("aaa", 24);
        Person p3 = new Person("ddd", 23);
        Person p4 = new Person("ccc", 22);
        Person p5 = new Person("ddd", 26);
        Person p6 = new Person("ddd", 26);
        person.add(p1);
        person.add(p2);
        person.add(p3);
        person.add(p4);
        person.add(p5);
        person.add(p6);
        System.out.println("元素个数:" + person.size());
        System.out.println(person.toString());
        //删除
//        System.out.println(person.remove(p1));
//        System.out.println(person.remove(new Person("ddd", 26)));
//        System.out.println(person.toString());
        //遍历
        System.out.println("====================增强for===================");
        for (Person p: person) {
            System.out.println(p);
        }
        System.out.println("====================迭代器===================");
        Iterator<Person> iterator = person.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        //判断
        System.out.println(person.contains(p1));
        System.out.println(person.contains(new Person("ddd", 26)));
    }
}
代码语言:javascript
复制
package com.framework.set.treeset;

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

/*treeset集合的使用
Comparator:实现定制比较(比较器)
Comparable:可比较的
 */
public class Demo03 {
    public static void main(String[] args) {
        //创建集合,并指定比较规则(匿名内部类,无须让person实现Comparable接口)
        TreeSet<Person> person = new TreeSet<>(new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                int n1 = o1.getAge() - o2.getAge();
                int n2 = o1.getName().compareTo(o2.getName());
                return n1==0?n2:n1;
            }
        });
        Person p1 = new Person("bbb", 21);
        Person p2 = new Person("aaa", 24);
        Person p3 = new Person("ddd", 23);
        Person p4 = new Person("ccc", 22);
        Person p5 = new Person("ddd", 26);
        Person p6 = new Person("zzz", 26);
        person.add(p1);
        person.add(p2);
        person.add(p3);
        person.add(p4);
        person.add(p5);
        person.add(p6);
        System.out.println("元素个数:" + person.size());
        System.out.println(person.toString());
    }
}
代码语言:javascript
复制
package com.framework.set.treeset;

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

/*
使用treeSet集合实现字符串按照长度进行排序
 */
public class Demo04 {
    public static void main(String[] args) {
        TreeSet<String> s = new TreeSet<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                int n1 = o1.length() - o2.length();
                int n2 = o1.compareTo(o2);
                return n1==0?n2:n1;
            }
        });
        s.add("helloword");
        s.add("zhangsan");
        s.add("lisi");
        s.add("xian");
        s.add("nanjing");
        s.add("cat");
        System.out.println("元素个数:" + s.size());
        System.out.println(s.toString());
    }
}

6.Map体系集合

Map接口的特点:

  • 用于存储任意键值对(Key-Value)
  • 键:无序、无下标、不允许重复
  • 值:无序、无下标、允许重复

6.1Map父接口

Map接口的使用

代码语言:javascript
复制
package com.framework.map;

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

/*
Map接口的使用
特点:1.存储键值对2.键不能重复,值可以重复3.无序
 */
public class Demo01 {
    public static void main(String[] args) {
        //创建集合
        Map<String, String> map = new HashMap<>();
        //添加元素
        map.put("cn","中国");
        map.put("up","英国");
        map.put("usa","美国");
        map.put("cn1","中国");
        System.out.println("元素个数:" + map.size());
        System.out.println(map.toString());
        //删除
        map.remove("cn1");
        System.out.println(map.toString());
        //遍历
        System.out.println("====================keySet=====================");
        //Set<String> keySet = map.keySet();
        //增强for
        for (String s: map.keySet()) {
            System.out.println(s+": "+map.get(s));
        }
        System.out.println("====================entrySet===================");
        //Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String,String> entry: map.entrySet()) {
            System.out.println(entry.getKey()+": "+entry.getValue());
        }
    }
}

6.2Map集合的实现类

HashMap

  • 线程不安全,运行效率快,允许用null作为key或是value
代码语言:javascript
复制
package com.framework.map;



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

/*
HashMap集合的使用
存储结构:哈希表
 */
public class HashMapDemo {
    public static void main(String[] args) {
        //创建集合
        HashMap<Student, String> students = new HashMap<>();
        //添加元素
        Student s1 = new Student("赵", 12345);
        Student s2 = new Student("王",12344);
        Student s3 = new Student("李",12343);
        students.put(s1,"北京");
        students.put(s2,"郑州");
        students.put(s3,"周口");
        students.put(new Student("李",12343),"杭州");
        System.out.println("元素个数:" + students.size());
        System.out.println(students.toString());
        //删除
        students.remove(s1);
        System.out.println(students.size());
        //遍历
        System.out.println("====================keySet=====================");
        for (Student s: students.keySet()) {
            System.out.println(s+": "+students.get(s));
        }
        System.out.println("====================entrySet===================");
        Set<Map.Entry<Student, String>> entries = students.entrySet();
        for (Map.Entry<Student,String> stu: entries) {
            System.out.println(stu.getKey() + ": " + stu.getValue());
        }
        //判断
        System.out.println(students.containsKey(s1));
        System.out.println(students.containsKey(new Student("李",12343)));
        System.out.println(students.containsValue("杭州"));
    }
}

HashTable

  • Properties是HashTable是子类,要求key和value都是String。通常用于配置文件的读取

TreeMap

  • 实现了SortedMap接口(是Map的子接口),可以对key自动排序
代码语言:javascript
复制
package com.framework.map;

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

public class TreeMapDemo {
    public static void main(String[] args) {
        //创建集合
        TreeMap<Student, String> treeMap = new TreeMap<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int i = o1.getStuNo() - o2.getStuNo();
                return i;
            }
        });
        Student s1 = new Student("赵", 12345);
        Student s2 = new Student("王",12344);
        Student s3 = new Student("李",12343);
        treeMap.put(s1,"北京");
        treeMap.put(s2,"深圳");
        treeMap.put(s3,"杭州");
        treeMap.put(new Student("李",12343),"南京");
        System.out.println("元素个数:" + treeMap.size());
        System.out.println(treeMap.toString());
        //删除
        //treeMap.remove(s3);
        //treeMap.remove(new Student("李",12343));
        System.out.println(treeMap.size());
        //遍历
        System.out.println("====================keySet=====================");
        for (Student student: treeMap.keySet()) {
            System.out.println(student.toString()+"="+treeMap.get(student));
        }
        System.out.println("====================entrySet===================");
        for (Map.Entry<Student,String> entry : treeMap.entrySet()) {
            System.out.println(entry.toString());
        }
        //判断
        System.out.println(treeMap.containsKey(s1));
        System.out.println(treeMap.containsValue("南京"));
        System.out.println(treeMap.containsKey(new Student("李",12343)));
    }
}

7.Collections工具类

集合工具类,定义了除了存取以外的集合常用方法

代码语言:javascript
复制
package com.framework.collection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CollectionsDemo01 {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(20);
        list.add(5);
        list.add(10);
        list.add(30);
        list.add(50);
        //sort排序
        System.out.println("排序之前"+list.toString());
        Collections.sort(list);
        System.out.println("排序之后"+list.toString());
        //binarySearch(二分查找)
        System.out.println("=================================");
        int i = Collections.binarySearch(list, 24);
        System.out.println(i);
        //copy复制
        System.out.println("=================================");
        ArrayList<Integer> arrayList = new ArrayList<>();
        for (int j = 0; j < list.size(); j++) {
            arrayList.add(0);
        }
        Collections.copy(arrayList,list);
        System.out.println(arrayList.toString());
        //reverse反转
        System.out.println("=================================");
        Collections.reverse(arrayList);
        System.out.println(arrayList.toString());
        //shuffle 打乱
        System.out.println("=================================");
        Collections.shuffle(arrayList);
        System.out.println(arrayList.toString());
        //list集合转成数组
        System.out.println("=================================");
        Integer[] arr = list.toArray(new Integer[0]);
        System.out.println(arr.length);
        System.out.println(Arrays.toString(arr));
        //数组转成集合
        System.out.println("=================================");
        String[] names = {"zhangsan","lisi","wangwu"};
        //数组转成集合之后,集合是受限集合,不能添加和删除
        List<String> list1 = Arrays.asList(names);
        System.out.println(list1.toString());

        System.out.println("=================================");
        //基本类型数据转成集合,不能用int,需要修改为引用类型
        Integer[] nums = {100, 200, 300, 400, 500};
        List<Integer> list2 = Arrays.asList(nums);
        System.out.println(list2.toString());
    }
}

8.Properties

Properties:属性集合

特点:

  • 存储属性名和属性值
  • 属性名和属性值都是字符串类型
  • 没有泛型
  • 和流有关
代码语言:javascript
复制
package com.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * 演示Properties集合的使用
 */
public class PropertiesDemo {
    public static void main(String[] args) throws Exception {
        //创建集合
        Properties properties = new Properties();
        //添加数据
        properties.setProperty("username","张三");
        properties.setProperty("age","20");
        System.out.println(properties.toString());
        //遍历
        System.out.println("===================keySet==================");
        Set<Object> objects = properties.keySet();
        for (Object o: objects) {
            System.out.println(o.toString() + ": " + properties.get(o));
        }
        System.out.println("===================entrySet==================");
        for (Map.Entry<Object, Object> o : properties.entrySet()) {
            System.out.println(o.getKey() + ": " + o.getValue());
        }
        System.out.println("===================stringPropertyNames()==================");
        Set<String> strings = properties.stringPropertyNames();
        for (String s: strings) {
            System.out.println(s + ": " + properties.getProperty(s));
        }
        //和流有关的方法
//        System.out.println("===================list方法==================");
//        PrintWriter pw = new PrintWriter("/Users/zhaoliang/IdeaProjects/io流/a1.txt");
//        properties.list(pw);
//        pw.close();
        System.out.println("===================store方法  保存==================");
        FileOutputStream fos = new FileOutputStream("/Users/zhaoliang/IdeaProjects/io流/a2.txt");
        properties.store(fos,"注释");
        fos.close();
        System.out.println("===================load方法  加载==================");
        FileInputStream fis = new FileInputStream("/Users/zhaoliang/IdeaProjects/io流/a2.txt");
        properties.load(fis);
        fis.close();
        System.out.println(properties.toString());
    }
}

9.面试题

List<Map<String,String>>遍历

代码语言:javascript
复制
package com.framework;

import java.util.*;

//List<Map<String,String>>遍历
public class Test {
    public static void main(String[] args) {
        List<Map<String, String>> listMaps = new ArrayList<Map<String, String>>();

        Map<String, String> map1 = new HashMap<String, String>();
        map1.put("aaa", "111");
        map1.put("bbb", "222");
        map1.put("ccc", "333");
        listMaps.add(map1);

        Map<String, String> map2 = new HashMap<String, String>();
        map2.put("11", "aa");
        map2.put("22", "bb");
        map2.put("33", "cc");
        listMaps.add(map2);

        //方式1:
        for (Map<String, String> map : listMaps) {
            for (String s : map.keySet()) {
                System.out.print(map.get(s) + "  ");
            }
        }
        System.out.println();
        System.out.println("-----------------------------");

        //方式2:
        for (int i = 0; i < listMaps.size(); i++) {
            Map<String, String> map = listMaps.get(i);
            Iterator iterator = map.keySet().iterator();
            while (iterator.hasNext()) {
                String string = (String) iterator.next();
                System.out.println(map.get(string));
            }
        }
        System.out.println("-----------------------------");

        //方式3:
        for (Map<String, String> map : listMaps) {
            for (Map.Entry<String, String> m : map.entrySet()) {
                System.out.print(m.getKey() + "    ");
                System.out.println(m.getValue());
            }
        }
        System.out.println("-----------------------------");
    }

}
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2022-05-31,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 IT技术订阅 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.集合和数组的区别
  • 2.Collection体系集合
    • 2.1Collection父接口
    • 3.List集合
      • 3.1List实现类
      • 4.泛型
        • 4.1泛型类
          • 4.2泛型接口
            • 4.3泛型方法
              • 4.4泛型集合
              • 5.Set子接口
                • 5.1Set实现类
                • 6.Map体系集合
                  • 6.1Map父接口
                    • 6.2Map集合的实现类
                    • 7.Collections工具类
                    • 8.Properties
                    • 9.面试题
                    领券
                    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档