jay2home

导航

 

集合

集合是一种容器的规范。区别于数组:集合的长度可变,自动扩容;数据可以存储任意类型,包括基本和对象引用,而集合只存储对象引用,若像存基本类型需要对应的包装类。

Collection是单列集合的根,其下两个重要的自接口List和Set。这种接口的实现类都非常常用。尤其是ArrayList和HashSet。在java.util包下

Collection是所有单列集合的父接口,因此在Collection中定义了单列集合(List和Set)通用的一些方法,这些方法可用于操作所有的单列集合。方法如下:

  • public boolean add(E e): 把给定的对象添加到当前集合中 。
  • public void clear() :清空集合中所有的元素。
  • public boolean remove(E e): 把给定的对象在当前集合中删除。
  • public boolean contains(Object obj): 判断当前集合中是否包含给定的对象。
  • public boolean isEmpty(): 判断当前集合是否为空。
  • public int size(): 返回集合中元素的个数。
  • public Object[] toArray(): 把集合中的元素,存储到数组中

用迭代器集合遍历

list.iterator();

while(it.hasNext()){

  Object s = it.next();

  //s

}
 public class IteratorDemo {
		public static void main(String[] args) {
		// 使用多态方式 创建对象
		Collection<String> coll = new ArrayList<String>();
    // 添加元素到集合
    coll.add("串串星人");
    coll.add("吐槽星人");
    coll.add("汪星人");
    //遍历
    //使用迭代器 遍历   每个集合对象都有自己的迭代器
    Iterator<String> it = coll.iterator();
    //  泛型指的是 迭代出 元素的数据类型
    while(it.hasNext()){ //判断是否有迭代元素
        String s = it.next();//获取迭代出的元素
        System.out.println(s);
    }
}

List接口

继承Collection,并且根据索引操作集合

  • public void add(int index, E element): 将指定的元素,添加到该集合中的指定位置上。
  • public E get(int index):返回集合中指定位置的元素。
  • public E remove(int index): 移除列表中指定位置的元素, 返回的是被移除的元素。
  • public E set(int index, E element):用指定元素替换集合中指定位置的元素,返回值的更新前的元素。

ArrayList

java.util.ArrayList。基于数组的集合,元素增删慢,查找快,由于日常开发中使用最多,用于查询数据、遍历数据。

但要注意ArrayList的特点,许多程序员开发时非常随意地使用ArrayList完成任何需求,并不严谨,这种用法是不提倡的。

LinkedList

基于双向链表实现的集合。方便元素添加、删除的集合,首尾操作。可以作为队列和堆栈使用

  • public void addFirst(E e):将指定元素插入此列表的开头。
  • public void addLast(E e):将指定元素添加到此列表的结尾。
  • public E getFirst():返回此列表的第一个元素。
  • public E getLast():返回此列表的最后一个元素。
  • public E removeFirst():移除并返回此列表的第一个元素。
  • public E removeLast():移除并返回此列表的最后一个元素。
  • public E pop():从此列表所表示的堆栈处弹出一个元素。
  • public void push(E e):将元素推入此列表所表示的堆栈。
  • public boolean isEmpty():如果列表不包含元素,则返回true。

Set接口

继承Collection且比Collection接口更加严格了。与List接口不同的是,Set接口都会以某种规则保证存入的元素不出现重复。有多种实现:

HashSet

基于HashMap实现的Set。Hash是无序的

HashSet保证元素唯一,可是元素存放进去是没有顺序的,那么我们要保证有序,怎么办呢?

LinkedHashSet

在HashSet下面有一个子类java.util.LinkedHashSet,它是链表和哈希表组合的一个数据存储结构。

TreeSet

TreeSet集合是Set接口的一个实现类,底层依赖于TreeMap,是一种基于红黑树的实现,其特点为:

  1. 元素唯一
  2. 元素没有索引
  3. 使用元素的自然顺序对元素进行排序,或者根据创建 TreeSet 时提供的 Comparator 比较器
    进行排序,具体取决于使用的构造方法:

Collections

常用功能

  • java.utils.Collections是集合工具类,用来对集合进行操作。

    常用方法如下:

  • public static void shuffle(List<?> list):打乱集合顺序。

  • public static <T> void sort(List<T> list):将集合中元素按照默认规则排序。

  • public static <T> void sort(List<T> list,Comparator<? super T> ):将集合中元素按照指定规则

Comparator比较器

public class Demo {
    public static void main(String[] args) {
        // 创建四个学生对象 存储到集合中
        ArrayList<Student> list = new ArrayList<Student>();

        list.add(new Student("rose",18));
        list.add(new Student("jack",16));
        list.add(new Student("abc",20));
        Collections.sort(list, new Comparator<Student>() {
          @Override
            public int compare(Student o1, Student o2) {
            return o1.getAge()-o2.getAge();//以学生的年龄升序
         }
        });

        for (Student student : list) {
            System.out.println(student);
        }
    }
}
Student{name='jack', age=16}
Student{name='rose', age=18}
Student{name='abc', age=20}

可变参数

修饰符 返回值类型 方法名(参数类型... 形参名){ }

public static int getSum(int... arr) {
	int sum = 0;
	for (int a : arr) {
	sum += a;
	}
	return sum;
}

注意:

1.一个方法只能有一个可变参数

2.如果方法中有多个参数,可变参数要放到最后。

Map

与Collection单列集合相对的,是Map双列集合。

常用子类接口:

  • HashMap
    • 存储数据采用的哈希表结构,元素的存取顺序不能保证一致。由于要保证键的唯一、不重复,需要重写键的hashCode()方法、equals()方法。
  • LinkedHashMap
    • 采用的哈希表结构+链表结构。通过链表结构可以保证元素的存取顺序一致;通过哈希表结构可以保证的键的唯一、不重复,需要重写键的hashCode()方法、equals()方法。
  • TreeMap
    • 基于红黑树;可以对元素的进行排序,排序方式有两种:自然排序比较器排序

Map接口

  • public V put(K key, V value): 把指定的键与指定的值添加到Map集合中。
  • public V remove(Object key): 把指定的键 所对应的键值对元素 在Map集合中删除,返回被删除元素的值。
  • public V get(Object key) 根据指定的键,在Map集合中获取对应的值。
  • public Set<K> keySet(): 获取Map集合中所有的键,存储到Set集合中。
  • public Set<Map.Entry<K,V>> entrySet(): 获取到Map集合中所有的键值对对象的集合(Set集合)。
  • public boolean containKey(Object key):判断该集合中是否有此键。

Map<String,String> name = HashMap<>();

Map遍历

Map中一个键对应一个值,键值对被封装为了Entry 项 对象。

遍历Map的思路:

获取键,获取值

  • public Set<K> keySet() 获取所有键的集合
  • public V get(Object key) 根据指定的键,在Map集合中获取对应的值。

获取键值对,取出键,取出值

  • public Set<K> keySet(): 获取Map集合中所有的键,存储到Set集合中。

    Entry有如下方法

    • public K getKey():获取Entry对象中的键。
    • public V getValue():获取Entry对象中的值。

HashMap

  • 当给HashMap中存放自定义对象时,如果自定义对象作为key存在,这时要保证对象唯一,必须复写对象的hashCode和equals方法(如果忘记,请回顾HashSet存放自定义对象)。
  • HashMap是无序的。如果要保证map中存放的key和取出的顺序一致,可以使用java.util.LinkedHashMap集合来存放。

自定义一个作为键的类

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

    //构造方法
    //get/set
    @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);
    }
}

LinkedHashMap

使用LinkedHashMap使元素有序,存的顺序就是取的顺序

public class LinkedHashMapDemo {
    public static void main(String[] args) {
        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
        map.put("邓超", "孙俪");
        map.put("李晨", "范冰冰");
        map.put("刘德华", "朱丽倩");
        Set<Entry<String, String>> entrySet = map.entrySet();
        for (Entry<String, String> entry : entrySet) {
            System.out.println(entry.getKey() + "  " + entry.getValue());
        }
    }
}

TreeMap

TreeMap集合和Map相比没有特有的功能,底层的数据结构是红黑树.

特点使对元素的进行排序,排序方式有两种:自然排序比较器排序;到时使用的是哪种排序,取决于我们在创建对象的时候所使用的构造方法;

public TreeMap()                                    使用自然排序
public TreeMap(Comparator<? super K> comparator)    比较器排

使用比较器

TreeMap<Student, String> map = new TreeMap<Student, String>(new Comparator<Student>() {
    	@Override
    	public int compare(Student o1, Student o2) {
      		//先按照年龄升序
      		int result = o1.getAge() - o2.getAge();
      		if (result == 0) {
        		//年龄相同,则按照名字的首字母升序
        		return o1.getName().charAt(0) - o2.getName().charAt(0);
      		} else {
        		//年龄不同,直接返回结果
        		return result;
      		}
    	}
  	});
posted on 2025-05-06 09:58  Jay404  阅读(12)  评论(0)    收藏  举报