Collection集合的学习

一、Collection的学习

在这里插入图片描述

1、共性的方法

public boolean add()
public void clear() :清空集合的元素,集合对象还在
public boolean remove()
public boolean contains() 是否包含某个元素
public boolean isEmpty()
public int size()
public Object[] toArray()

2、Iterator迭代器

迭代器也可以用增强for循环来实现

 Iterator<String> iterator = collection.iterator();
 while (iterator.hasNext()){
      System.out.println(iterator.next());
 }
for(String a:collection){
 	 System.out.println(a);
}

3、linkedList

boolean add(E e)
将指定元素添加到此列表的结尾。
void add(int index, E element)
在此列表中指定的位置插入指定的元素。
boolean addAll(Collection<? extends E> c)
添加指定 collection 中的所有元素到此列表的结尾,顺序是指定 collection 的迭代器返回这些元素的顺序。
boolean addAll(int index, Collection<? extends E> c)
将指定 collection 中的所有元素从指定位置开始插入此列表。
void addFirst(E e)
将指定元素插入此列表的开头。
void addLast(E e)
将指定元素添加到此列表的结尾。
void clear()
从此列表中移除所有元素。
boolean contains(Object o)
如果此列表包含指定元素,则返回 true。

4、HashSet

HashSet存储的是无序集合,且不重复,重复的概念是hashcode的值相等且equase比较也相等
,String重写了hashcode和equals方法。自定义的类也需要重写hashcode和equals方法。

5、LinkedHashSet

此实现与 HashSet 的不同之外在于,后者维护着一个运行于所有条目的双重链接列表。此链接列表定义了迭代顺序,即按照将元素插入到 set 中的顺序(插入顺序)进行迭代。注意,插入顺序不 受在 set 中重新插入的 元素的影响。

二、Collections集合工具类

static boolean addAll(Collection<? super T> c, T… elements)
将所有指定元素添加到指定 collection 中。

 List<String> stringList = new ArrayList<>();
 Collections.addAll(stringList,"b","c","d","e");

static void shuffle(List<?> list)
使用默认随机源对指定列表进行置换。打乱集合顺序

Collections.shuffle(stringList);

Collections.sort 排序

方法1:

String和Integer都实现了Comparable<泛型>这个接口,并且重写了**public int compareTo()**这个方法,升序排序。this - 参数 == 升序排序,参数 - this == 降序排序

List<String> stringList = new ArrayList<>();
Collections.addAll(stringList,"b","a","d","c");
Collections.sort(stringList); //[a, b, c, d]

自定义一个Person类,按照年龄升序排序(this - 参数 == 升序排序,参数 - this == 降序排序)


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

    @Override
    public int compareTo(Person o) {
        return this.age-o.age; //this - 参数 == 升序排序,参数 - this == 降序排序
    }
}

方法2:
List<Person2> stringList = new ArrayList<>();
Collections.addAll(stringList,new Person2(18,"张三"),new Person2(15,"李四"),new Person2(19,"王五"));
Collections.sort(stringList, new Comparator<Person2>() {
    @Override
    public int compare(Person2 o1, Person2 o2) {
        return o1.getAge()-o2.getAge();
    }
});
System.out.println(stringList);

Comparable和Comparator 的区别
Comparable: 自己(this)和别人(参数比较),自己需要实现Comparable接口,重写compareTo方法
Comparator: 相当找第三方来比较,传递一个接口的匿名内部类

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值