ruijiege

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

List

是一个接口实现可重复有序的存储,有ArrayList和Linked List两种实现类中使用的方法为add()list.iterrator获得迭代器,通过迭代器进行遍历

区别在于数组和链表的区别

数组查询容易,增加和删除难,

链表增删容易,查询需要遍历;

Set

一个不可重复无序的存储方式,也是常用方法为add和list.iterrator获得迭代器来遍历

hashSet底层为hashmap当我们判断是否为相同值的时候需要同时覆写hashcode和equals方法

TreeSet判断重复为自然排序和定制排序(类似于中介者模式)

自然排序为实现comparable接口实现comparaTO方法的返回值如果为0就不可重复,如果为1或者-1为可重复

package cn.jiedada.TreeSet;

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

public class Test {
    /*也是Set的实现类
     * 不可重复的无序存储
     * 遍历方法
     * 不可重复的实现
     * 自然排序compareTo和定制排序Comparable这个接口
     * 定制排序
     * */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TreeSet treeSet = new TreeSet();
        Teacher teacher1 = new Teacher("李老师", 42);
        Teacher teacher2 = new Teacher("李老师", 42);
        //在添加的时候只能添加同一类的实列
    /*    Exception in thread "main" java.lang.ClassCastException: 
            cn.jiedada.TreeSet.Teacher cannot be cast to java.lang.Comparable*/
        treeSet.add(teacher1);
        treeSet.add(teacher2);
        /*Exception in thread "main" java.lang.ClassCastException: 
         * cn.jiedada.TreeSet.Teacher cannot be cast to java.lang.Integer*/
        //treeSet.add(1);
        System.out.println(treeSet);
        /*TreeSet(Comparator<? super E> comparator) */
    
    }

}
class Teacher implements Comparable{
    String name;
    Integer age;
    public Teacher(String name, Integer age) {
        super();
        this.name = name;
        this.age = age;
    }
    @Override
    public int compareTo(Object o) {
        // TODO Auto-generated method stub
        return 0;
    }
    @Override
    public String toString() {
        return "Teacher [name=" + name + ", age=" + age + "]";
    }
    
}
View Code

定制排序为compartor接口我们可以为我们自己指定的规则判断是否重复

package cn.jiedada.TreeSet;

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

public class Test1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        TreeSet treeSet=new TreeSet(new Comparator() {

            @Override
            public int compare(Object o1, Object o2) {
                Student student1=(Student)o1;
                Student student2=(Student)o2;
                return student1.age.compareTo(student2.age);
            }
        });
        Student student = new Student("李鹏", 18);
        Student student2 = new Student("小张", 18);
        treeSet.add(student);
        treeSet.add(student2);
        System.out.println(treeSet);
    }

}
class Student{
    String name;
    Integer age;
    public Student(String name, Integer age) {
        super();
        this.name = name;
        this.age = age;
    }
    
}
View Code

 

posted on 2019-08-02 19:58  哦哟这个怎么搞  阅读(163)  评论(0编辑  收藏  举报