常用对象API(集和框架--Collection)

/*
集和类的由来:
    对象用于封装特有数据,对象多了需要存储,如果对象的个数不确定。
    就使用集和容器进行存储。
集和特点:
    1.用于存储对象的容器。
    2.集和的长度是可变的。
    3.集和中不可以存储基本数据类型值。
集和容器因为内部数据结构不同,有多种具体容器,
不断向上抽取,形成集和框架。
框架的顶层Collection接口:
Collection常见方法:
    1.添加
        boolean add(Object obj);
        boolean addAll(Collection coll);
    2.删除
        boolean remove(Object obj);
        boolean removeAll(Collection coll);
        void clear();
    3.判断
        boolean contains(Object obj);
        boolean containsAll(Collection coll);
        boolean isEmpty();//判断是否有元素
    4.获取
        int size();
        iterator();//取出元素的方式,迭代器
    5.其他
        boolean retainAll();//取交集
        Object[] toArray();
*/

在这里插入图片描述

Collection coll = new ArrayList<>();
public static void show(Collection coll){
        //添加元素
        coll.add("abc1");
        coll.add("abc2");
        coll.add("abc3");
        //[abc1, abc2, abc3]
        //删除元素
        coll.remove("abc2");//[abc1, abc3]
        //集和的remove会改变集和长度
        //清空集和
        coll.clear();//[]
        System.out.println(coll.contains("abc1"));//false
        System.out.println(coll);
    }
public static void show1(Collection c1,Collection c2){
        //给c1添加元素
        c1.add("abc1");
        c1.add("abc2");
        c1.add("abc3");
        c1.add("abc4");
        //给c2添加元素
        c2.add("abc5");
        c2.add("abc6");
        c2.add("abc7");
        c2.add("abc8");
        //演示addAll()
        System.out.println("c1:"+c1);
        System.out.println("c2:"+c2);
        c1.addAll(c2);//将c2中的元素添加到c1中
        System.out.println(c1);
        System.out.println(c1.containsAll(c2));//true
        c1.removeAll(c2);//将两个集和中的相同元素从c1中删除
        System.out.println(c1);
        //演示containsAll();
        System.out.println(c1.containsAll(c2));//false
        //演示retainAll();
        c2.add("abc1");
        boolean b = c1.retainAll(c2);//取交集
        System.out.println(b);//true
        System.out.println("c1:"+c1);//[abc1]
    }

迭代器演示iterator()

Collection coll = new ArrayList<>();
        coll.add("abc1");
        coll.add("abc2");
        coll.add("abc3");
        coll.add("abc4");
        //使用了Collection中的iterator()方法,调用集和中的迭代器方法,是为了获取集和中的迭代器对象
        Iterator it = coll.iterator();
        // System.out.println(it.next());//abc1
        // System.out.println(it.next());//abc2
        // System.out.println(it.next());//abc3
        // System.out.println(it.next());//abc4
        // System.out.println(it.next());//Exception in thread "main" java.util.NoSuchElementException
        while(it.hasNext()){
            System.out.println(it.next());
        }
        for(Iterator i = coll.iterator();i.hasNext();){
            System.out.println(i.next());
        }

List

import java.util.List;//java.awt.List
/*
Collection:
    1.List:有序(存入和取出的顺序一致),元素都有索引(角标),元素可以重复。
    2.Set:元素不能重复,无序。
*/
/*
List:特有的常见方法,有一个共性特点:都可以操作角标
    1.添加
        void add(E e);
        void add(int index,E e);
        void addAll(int index,Collection coll);
    2.删除
        Object remove(index);
    3.修改
        Object set(index,element);
    4.获取
        Object get(index);
        int indexOf(Object);
        int lastIndexOf(Object);
        List subList(from,to);
List集和可以完成对元素的增删改查
*/
public class packDemo{
    public static void main(String[] args){
        List list = new ArrayList<>();
        show(list);
    }
    public static void show(List list){
        list.add("abc1");
        list.add("abc2");
        list.add("abc3");
        System.out.println(list);//[abc1, abc2, abc3]
        //插入元素
        list.add(1,"abc4");
        System.out.println(list);//[abc1, abc4, abc2, abc3]
        //删除元素
        System.out.println("remove:"+list.remove(2));//remove:abc2
        //修改元素
        System.out.println(list.set(0, "hello"));//[hello, abc4, abc3]
        System.out.println(list.get(0));//hello
        //获取子列表
        System.out.println(list.subList(0, 2));//[hello, abc4]
        System.out.println(list);
    }
}

ListIterator接口
引入

List list = new ArrayList<>();
// show(list);
list.add("abc1");
list.add("abc2");
list.add("abc3");
list.add("abc4");
Iterator it = list.iterator();
while(it.hasNext()){
    Object obj = it.next();
    if(obj.equals("abc2")){
    	list.add("hello");//Exception in thread "main" java.util.ConcurrentModificationException
             //在迭代器过程中,不要使用集和操作元素,容易出现异常
             //可以使用Iterator接口的子接口ListIterator来完成在迭代中对元素进行更多操作。
      }
    else{
        System.out.println("next:"+obj);
    }
 }
System.out.println(list);
}

使用

List list = new ArrayList<>();
        // show(list);
        list.add("abc1");
        list.add("abc2");
        list.add("abc3");
        list.add("abc4");
        ListIterator it = list.listIterator();//获取列表迭代器
        //可以实现在迭代过程中完成对元素的增删改查
        //注意:只有list集和具备该迭代功能
        while(it.hasNext()){
            Object obj = it.next();
            if(obj.equals("abc2")){
                it.set("hello");//[abc1, hello, abc3, abc4]
            }
        }
        //逆序遍历
        while(it.hasPrevious()){
            System.out.println(it.previous());
        }
        System.out.println(list);
    }
/*
List:
    1.Vector:内部是数组数据结构,是同步的。增删查询都很慢
    2.ArrayList:内部是数组数据结构,是不同步的,替代了Vector.查询的速度快。
    3.LinkedList:内部是链表数据结构,是不同步的,增删元素的速度很快。
*/
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
// List:
    // 1.Vector
    // 2.ArrayList
    // 3.LinkedList
//集和框架:Vector
import java.util.Vector;
public class packDemo{
    public static void main(String[] args){
        linkedListDemo();
        //
    }
    //Vector
    public static void vectorDemo(){
        Vector v = new Vector();
        v.addElement("abc1");
        v.addElement("abc2");
        v.addElement("abc3");

        Enumeration en = v.elements();
        while(en.hasMoreElements()){
            System.out.println("nextelement:"+en.nextElement());
        }
        Iterator it = v.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
    }
    //LinkedList
    public static void linkedListDemo(){
        LinkedList list = new LinkedList();
        list.add("abc1");
        list.add("abc2");
        list.add("abc3");
        list.addFirst("hello");
        System.out.println(list.getFirst());//hello 获取第一个但不删除
        System.out.println(list.getFirst());//hello
        System.out.println(list.removeFirst());//hello 获取元素并删除
        Iterator it = list.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
        while(!list.isEmpty()){
            System.out.println(list.removeFirst());//list.removeLast()
        }
    }
}

LinkedList实现队列

package mypackage;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;//java.awt.List
import java.util.ListIterator;
// LinkedList练习:
    // 请使用LinkedList来模拟一个堆栈或者队列数据结构
    // 堆栈:先进后出
    // 队列:先进先出
        // 应该描述这样一个容器,给使用者提供一个容器对象,完成这两种结构中的一种
/*
LinkedList:
    addFirst();
    addLast();

    getFirst();//获取但不移除,如果链表为空,抛出NoSuchElementException.
    getLast();

    peekFirst();//获取但不移除,如果链表为空,返回null.
    peekLast();

    removeFirst();//获取并移除,如果链表为空,抛出NoSuchElementException.
    removeLast();

    pollFirst();//获取并移除,如果链表为空,返回null.
    pollLast();
*/
import java.util.Vector;

class DuiLie{
    private LinkedList list;
    DuiLie(){
        list = new LinkedList<>();
    }
    public boolean myAdd(Object obj){
        if(list.add(obj))
            return true;
        else
            return false;
    } 
    public Object myGet(){
        return list.removeFirst();
    }
    public boolean isEmpty(){
        return list.isEmpty();
    }
}
public class packDemo{
    public static void main(String[] args){
        DuiLie dl = new DuiLie();
        dl.myAdd("abc1");
        dl.myAdd("abc2");
        dl.myAdd("abc3");
        while(!dl.isEmpty()){
            System.out.println(dl.myGet());
        }
        // abc1
        // abc2
        // abc3
    }
}

ArrayList集和存储自定义对象

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;//java.awt.List
import java.util.ListIterator;

import java.util.Vector;

class Person{
    String name;
    int age;
    Person(String name,int age){
        this.name = name;
        this.age = age;
    }
    String getName(){
        return this.name;
    }
    int getAge(){
        return this.age;
    }
}
public class packDemo{
    public static void main(String[] args){
        ArrayList al = new ArrayList<>();
        al.add(new Person("li", 24));
        al.add(new Person("kang", 24));
        al.add(new Person("zhu", 23));

        Iterator it = al.iterator();
        while(it.hasNext()){
            Person p = (Person)it.next();
            System.out.println(p.getName()+"--"+p.getAge());
        }
    }
}

HashSet集和

import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;//java.awt.List
import java.util.ListIterator;
/**
 * Set:元素不可以重复,是无序
 *      Set接口中的方法和Collection一致
 *      1.HashSet:由哈希表支持,不保证set的迭代顺序,是不同步的
 *      2.TreeSet:可以对Set集和中的元素进行排序。是不同步的。
 * 				判断元素唯一性的方式:根据比较方法的返回结果是否是0,是0就是相同元素,不存。
 * 				TreeSet对元素进行排序的方式一:
 * 					让元素自身具备比较方法,实现Compareble接口,覆盖compareTo方法。
 * 				如果不要按照对象中具备的自然顺序进行排序,如果对象中不具备自然顺序,可以使用
 * 				TreeSet集和第二种排序方式二:
 * 					让集和自身具备比较功能,定义一个类实现Comparator接口,覆盖compare方法。
 * 					将该类对象作为参数传递给TreeSet集和的构造函数。
 */
/**
 * 哈希表确定元素是否相同
 * 1.判断的是两个元素的哈希值是否相同。
 *      如果相同,再判断两个对象的内容是否相同
 * 2.判断哈希值相同,其实判断的是对象的hashCode方法。
 * 判断内容相同,用的是equals方法。
 * 注意:
 * 如果哈希值不同,是不需要判断equals。
 */
class Person{
    String name;
    int age;
    Person(String name,int age){
        this.name = name;
        this.age = age;
    }
    String getName(){
        return this.name;
    }
    int getAge(){
        return this.age;
    }
    //覆盖Object的hashCode方法
    public int hashCode(){
        System.out.println("hashcode...");
        return this.name.hashCode()+this.age;
    }
    public boolean equals(Object obj){
        System.out.println("equals...");
        Person p = (Person)obj;
        return this.name.equals(p.name) && this.age==p.age;
    }
    public String toString(){
        return this.name+":"+this.age;
    }
}
public class packDemo{
    public static void main(String[] args){
        hashSetDemo2();
    }
    public static void hashSetDemo(){
        HashSet hs = new HashSet<>();
        hs.add("hahah");
        hs.add("xixi");
        hs.add("hehe");
        hs.add("heihei");
        Iterator it = hs.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
    }
    /**
     * 往hashSet集和中存储Person对象。如果姓名和年龄相同,视为同一个人,视为相同元素。
     */
    public static void hashSetDemo2(){
        HashSet hs = new HashSet<>();
        /**
         * HashSet集和数据结构是哈希表,所以存储元素的时候。
         * 使用元素的hashCode方法来确定位置,如果位置相同,再通过元素的equals来确定是否相同。
         */
        hs.add(new Person("li", 24));
        hs.add(new Person("zhu", 23));
        hs.add(new Person("kang", 24));
        hs.add(new Person("kang", 24));
        Iterator it = hs.iterator();
        while(it.hasNext()){
            Person p = (Person)it.next();
            System.out.println(p.getName()+"..."+p.getAge());
        }
    }
}

集和框架练习

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;//java.awt.List
import java.util.ListIterator;

class Person{
    String name;
    int age;
    Person(String name,int age){
        this.name = name;
        this.age = age;
    }
    String getName(){
        return this.name;
    }
    int getAge(){
        return this.age;
    }
    //覆盖Object的hashCode方法
    public int hashCode(){
        System.out.println("hashcode...");
        return this.name.hashCode()+this.age;
    }
    public boolean equals(Object obj){
        System.out.println("equals...");
        Person p = (Person)obj;
        return this.name.equals(p.name) && this.age==p.age;
    }
    public String toString(){
        return this.name+":"+this.age;
    }
}
public class packDemo{
    public static void main(String[] args){
        ArrayList al = new ArrayList<>();
        // al.add("abc1");
        // al.add("abc1");
        // al.add("abc2");
        // al.add("abc2");
        al.add(new Person("kpp", 24));
        al.add(new Person("kpp", 24));
        al.add(new Person("kpp", 24));
        al.remove(new Person("kpp", 24));
        System.out.println(al);//[abc1, abc1, abc2, abc2]
        al = getSingleElement(al);
        System.out.println(al);//[abc1, abc2]
    }
    //集和框架练习
    public static ArrayList getSingleElement(ArrayList al){
        //1.定义一个临时容器
        ArrayList temp = new ArrayList<>();
        //2.迭代al集和
        Iterator it = al.iterator();
        while(it.hasNext()){
            Object obj = it.next();
            //3.判断被迭代到的元素是否在临时容器中存在
            if(!temp.contains(obj)){
                temp.add(obj);
            }
        }
        return temp;
    }
}
LinkedHashSet hs = new LinkedHashSet<>();//唯一
hs.add("abc1");
hs.add("haha");
hs.add("hehe");
hs.add("hehe");
hs.add("heihei");
hs.add("heihei");
Iterator it = hs.iterator();
while(it.hasNext()){
     System.out.println(it.next());
 }
// abc1
// haha
// hehe
// heihei

TreeSet

2.TreeSet:可以对Set集和中的元素进行排序。是不同步的。
 * 				判断元素唯一性的方式:根据比较方法的返回结果是否是0,是0就是相同元素,不存。
 * 				TreeSet对元素进行排序的方式一:
 * 					让元素自身具备比较方法,实现Compareble接口,覆盖compareTo方法。
 * 				如果不要按照对象中具备的自然顺序进行排序,如果对象中不具备自然顺序,可以使用
 * 				TreeSet集和第二种排序方式二:
 * 					让集和自身具备比较功能,定义一个类实现Comparator接口,覆盖compare方法。
 * 					将该类对象作为参数传递给TreeSet集和的构造函数。

Comapreble接口

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;//java.awt.List
import java.util.ListIterator;
import java.util.TreeSet;

class Person implements Comparable{
    String name;
    int age;
    Person(String name,int age){
        this.name = name;
        this.age = age;
    }
    //实现compareTo方法
    public int compareTo(Object obj) {
        Person p = (Person)obj;
        if(this.age>p.age)
            return 1;
        else if(this.age<p.age)
            return -1;
        return this.name.compareTo(p.name);//为了在set存放对象时不因为年龄相同视为同一对象不存储
        // int temp = this.age-p.age;
        // return temp==0?this.name.compareTo(p.name):temp;
    }
    String getName(){
        return this.name;
    }
    int getAge(){
        return this.age;
    }
    //覆盖Object的hashCode方法
    public int hashCode(){
        System.out.println("hashcode...");
        return this.name.hashCode()+this.age;
    }
    public boolean equals(Object obj){
        System.out.println("equals...");
        Person p = (Person)obj;
        return this.name.equals(p.name) && this.age==p.age;
    }
    public String toString(){
        return this.name+":"+this.age;
    }
}
public class packDemo{
    public static void main(String[] args){
            TreeSetDemo_obj();
        }
    public static void TreeSetDemo_obj() {
        TreeSet ts = new TreeSet<>();
        ts.add(new Person("pp", 24));
        ts.add(new Person("zz", 23));
        ts.add(new Person("ww", 25));
        ts.add(new Person("ss", 25));
        Iterator it = ts.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
    }
}

Comparator比较器

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;//java.awt.List
import java.util.ListIterator;
import java.util.TreeSet;
//创建根据person类对象name进行排序的比较器
class ComparatorByName implements Comparator{
    public int compare(Object o1,Object o2){
        Person p1 = (Person)o1;
        Person p2 = (Person)o2;
        int temp = p1.getName().compareTo(p2.getName());
        return temp==0?p1.getAge()-p2.getAge():temp;
    }
}
class Person{
    String name;
    int age;
    Person(String name,int age){
        this.name = name;
        this.age = age;
    }
    String getName(){
        return this.name;
    }
    int getAge(){
        return this.age;
    }
    
    public String toString(){
        return this.name+":"+this.age;
    }
}
public class packDemo{
    public static void main(String[] args){
            TreeSetDemo_obj();
        }
    public static void TreeSetDemo_obj() {
        TreeSet ts = new TreeSet<>(new ComparatorByName());//集和中定义比较器
        ts.add(new Person("pp", 24));
        ts.add(new Person("zz", 23));
        ts.add(new Person("ww", 25));
        ts.add(new Person("ss", 25));
        Iterator it = ts.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
    }
}

TreeSet练习–字符串长度排序

import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;//java.awt.List
import java.util.ListIterator;
import java.util.TreeSet;

class ComparatorByStringLength implements Comparator{
    public int compare(Object s1,Object s2){
        String st1 = (String)s1;
        String st2 = (String)s2;
        int temp = st1.length()-st2.length();
        return temp==0?st1.compareTo(st2):temp;
    }
}
public class packDemo{
    public static void main(String[] args){
        stringDemo();
        }
    //TreeSet练习--字符串长度排序
    public static void stringDemo(){
        TreeSet ts = new TreeSet<>(new ComparatorByStringLength());
        ts.add("hs");
        ts.add("asd");
        ts.add("a");
        ts.add("zf");
        ts.add("kjsh");
        Iterator it = ts.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值