java泛型

泛型概念

  • 泛型就是参数化类型
  • 适用于多种数据类型执行相同功能的代码
  • 泛型中的类型在使用时指定
  • 泛型归根到底就是“模板”

泛型类

/**
 * 自定义泛型类
 * 1、<>单个大写字母,尽可能见名知意
 * 2、
 * T Type
 * K V Key Value
 * E Element
 * 3、注意点:泛型不能使用在静态属性上
 * @author L J
 */
//(T --> type) 类型
public class Student<T>{
    private T javase;
    public Student() {
    }
    public Student(T javase) {
        this.javase = javase;
    }
    public T getJavase() {
        return javase;
    }
    public void setJavase(T javase) {
        this.javase = javase;
    }
}
/**
 * 自定义泛型类的使用
 * 在声明时指定具体的类型
 * 不能为基本类型
 * @author L J
 */
public class StudentTest {
    public static void main(String[] args) {
        Student<Integer> stu = new Student<Integer>();
        stu.setJavase(90);
        System.out.println(stu.getJavase());
    }
}

泛型接口

//泛型接口
public interface Comparator<T> {
    //全局常量
    public static final int MAX_VALUE = 1024;
    //在接口中只能在公共的抽象方法上使用泛型
    public abstract void compare(T t);
}

泛型方法

/**
 * 非泛型类中定义泛型方法
 * 定义:在返回类型前面加<字母>
 * @author L J
 *
 */
public class Method {
    //泛型方法
    public static <T> void test(T t) {
        System.out.println(t);
    }

    //T只能是List或List的实现类
    public static <T extends List> void test(T t) {
        t.add("aaa");
        System.out.println(t.get(0));
    }

    public static void main(String[] args) {
        test(1.5);  //1.5
        test(new ArrayList()); //aaa
    }
}

泛型继承

泛型类:

/**
 * 泛型父类,子类为富二代[子类类型个数>=父类类型个数]
 * 子类重写方法的参数类型-->随父类而定
 * 子类新增方法的参数类型-->随子类而定
 * 子类中使用父类的属性-->随父类而定
 * 子类中使用自己的属性-->随子类而定
 * @author L J
 */
public abstract class Father<T1, T2> {
    T1 age;
    public abstract void test(T2 name);
}

//保留泛型 --> 泛型子类
//1、全部保留
class C1<T2, T1> extends Father<T1, T2>{

    @Override
    public void test(T2 name) {
        //this.age --> T1
    }
}
//2、部分保留
class C2<T2, A> extends Father<Integer, T2>{

    @Override
    public void test(T2 name) {
        //this.age --> Integer
    }
}
//不保留泛型 --> 按需实现,也可以是泛型类
//1、具体类型
class C3<A, B> extends Father<Integer, String>{

    @Override
    public void test(String name) {
        //this.age --> Integer
    }
}
//2、没有类型 擦除
class C4 extends Father/*<Object, Object>*/{

    @Override
    public void test(Object name) {
        //this.age --> Object
    }
}

泛型接口:

/**
 * 泛型接口与泛型类同理
 * @author L J
 */
public interface InterfaceF<T> {
    //全局常量
    public static final int MAX_VALUE = 100;
    //公共抽象方法
    public abstract void test(T t);
}

//实现
class InterSub1<A> implements InterfaceF {
    @Override
    public void test(Object t) {

    }
}

class InterSub2<T, B> implements InterfaceF<T> {
    @Override
    public void test(T t) {

    }
}

class InterSub3 implements InterfaceF<Integer> {
    @Override
    public void test(Integer t) {

    }
}

泛型的擦除

public class Student<T>{
    private T javase;
    public Student() {
    }
    public Student(T javase) {
        this.javase = javase;
    }
    public T getJavase() {
        return javase;
    }
    public void setJavase(T javase) {
        this.javase = javase;
    }
}
public class StudentTest {
    public static void main(String[] args) {
        //泛型的擦除,[使用时|实现|继承]没有指定类型,编译不会类型检查
        Student student = new Student();
        //student.setJavase("aaa");
        student.setJavase(90);
        System.out.println(student.getJavase());
    }
}

通配符

/**
 * ? --> 通配符,类型不确定,用于[声明变量|形参上]
 * 通配符在以下情况不能使用:
 * 1、创建对象
 * 2、创建泛型类 泛型方法 泛型接口上
 * @author L J
 */
public class WildcardsTest {
    public static void main(String[] args) {
        //声明
        List<?> list = new ArrayList<Integer>();
        list = new ArrayList<String>();
        test(list);
        //编译错误,不能用于创建对象
        //list = new ArrayList<?>();
    }

    public static void test(List<?> list) {

    }

    /*不能用于创建泛型方法
    public static <?> void test2(List<?> list) {

    }
    */

    /*不能用于创建泛型类
    class Test<?> {

    }
    */
}

泛型上限:

/**
 * 继承链
 *      Object
 *        |
 *      Fruit
 *       / \
 *    Apple Pear
 *      |
 *  FujiApple
 * @author L J
 */
public class Fruit {

}
class Apple extends Fruit {

}
class Pear extends Fruit {

}
class FujiApple extends Apple {

}
/**
 *extends 泛型的上限  <=  
 *1、一般用于限制操作
 *2、不能使用在添加数据上面,一般用于数据读取操作
 *3、规则
 * List<Fruit> --> List<? extends Fruit>
 * List<Apple> --> List<? extends Fruit>
 * List<? extends Apple> --> List<? extends Fruit>
 * 不能存放
 * List<?> 相当于 List<? extends Object>
 * @author L J
 */
public class ExtendsTest {
    public static void main(String[] args) {
        Test<Fruit> t1 = new Test<Fruit>();
        Test<Apple> t2 = new Test<Apple>();
        Test<Pear> t3 = new Test<Pear>();
        Test<FujiApple> t4 = new Test<FujiApple>();
        //调用方法
        List<? extends Fruit> list1 = new ArrayList<Fruit>();
        test(list1);
        List<Fruit> list2 = new ArrayList<Fruit>();
        test(list2);
        List<Apple> list3 = new ArrayList<Apple>();
        test(list3);

        //? extends Apple
        List<? extends Apple> list4 = new ArrayList<FujiApple>();
        test(list4);

        //? --> 为什么错误:?等同于? extends Object
        //List<?> list5 = new ArrayList<Fruit>();
        //test(list5);

        List<FujiApple> list5 = new ArrayList<FujiApple>();
        test(list5);
    }

    public static void test(List<? extends Fruit> list) {
        /*
        list.add(new Apple());
        list.add(new FujiApple());
        list.add(new Pear());
        list.add(new Fruit());
        */
        list.add(null);
    }

    //泛型类
    static class Test<T extends Fruit> {

    }
}

泛型下限:

/**
 * super 泛型的下限 >=
 * 1、能够添加数据,不能添加父对象
 * 2、规则
 *  List<Fruit> --> List<? super Apple>
 *  List<Apple> --> List<? super Apple>
 *  List<? super Fruit> --> List<? super Apple>
 *  不能存放
 *  List<? super FujiApple> --> List<? super Apple>
 * @author L J 
 */
public class SuperTest {
    public static void main(String[] args) {
        List<Apple> list1 = new ArrayList<Apple>();
        test(list1);
        List<Fruit> list2 = new ArrayList<Fruit>();
        test(list2);
        List<Object> list3 = new ArrayList<Object>();
        test(list3);

        //规则
        List<? super Apple> list4 = new ArrayList<Apple>();
        test(list4);
        List<? super Fruit> list5 = new ArrayList<Object>();
        test(list5);
        List<? super FujiApple> list6 = new ArrayList<Object>();
        //test(list6);
        List<?> list7 = new ArrayList<Object>();
        //test(list7);
    }

    public static void test(List<? super Apple> list) {
        //不能添加父类对象
        list.add(new Apple());
        list.add(new FujiApple());
        //list.add(new Fruit());
    }
}

泛型嵌套

public class Student<T>{
    private T javase;
    public Student() {
    }
    public Student(T javase) {
        this.javase = javase;
    }
    public T getJavase() {
        return javase;
    }
    public void setJavase(T javase) {
        this.javase = javase;
    }
}
//班级泛型类
public class Class<T> {
    private T stu;

    public T getStu() {
        return stu;
    }

    public void setStu(T stu) {
        this.stu = stu;
    }
}
//测试泛型嵌套
public class StudentApp {
    public static void main(String[] args) {
        Student<String> stu = new Student<String>();
        stu.setJavase("A(优秀)");
        System.out.println(stu.getJavase()); //A(优秀)

        //泛型嵌套
        Class<Student<String>> cla = new Class<Student<String>>();
        cla.setStu(stu);
        System.out.println(cla.getStu().getJavase());   //A(优秀)
    }
}

泛型细节

/**
 *1、泛型没有多态
 *2、泛型没有数组 
 * @author L J
 */
public class Polymorphism {
    public static void main(String[] args) {
        //多态
        Fruit f = new Apple();
        //泛型没有多态
        //List<Fruit> list = new ArrayList<Apple>();
        List<? extends Fruit> list = new ArrayList<Apple>();

        //泛型没有数组
        //Fruit<String>[] arr = new Fruit<String>[10];

        //JDK1.7泛型简化
        //List<Fruit> list2 = new ArrayList<>();
    }
}

深入理解迭代器

/**
 * 实现一个带迭代器的ArrayList
 * 主要为了深入了解迭代器原理
 * 集合框架中的迭代器实现在AbstractList抽象类中
 * 深入:
 * 1、使用匿名内部类实现迭代器
 * 2、使用Iterable接口,实现增强for循环迭代
 * 3、泛型的使用
 * @author L J
 */
public class IterArrayList<E> implements Iterable<E>{
    //数组
    private Object[] elem = new Object[5];

    //大小
    private int size = 0;

    //获取容器大小
    public int size() {
        return size;
    }

    public void add(E ele) {
        if(size == elem.length) {//容量不够了
            elem = Arrays.copyOf(elem, elem.length + 5);
        }
        elem[size++] = ele; 
    }

    /*public Iterator iterator() {
        //局部内部类,相当于局部变量
        class Itr implements Iterator<E>{
            //游标,指针
            private int coursor = -1;

            //判断是否存在下一个
            public boolean hasNext() {
                return coursor + 1 < size;
            }

            //获取下一个
            public String next() {
                coursor++;
                return elem[coursor];
            }

            //删除下一个
            public void remove() {
                //移动数组元素
                System.arraycopy(elem, coursor + 1, elem, coursor, size - coursor - 1);
                size--;
                //指针回退
                coursor--;
            }
        }
        return new Itr();
    }*/

    @SuppressWarnings("unchecked")
    public Iterator<E> iterator() {
        return new Iterator(){ //创建Iterator接口的实现类[匿名]对象
            //游标,指针
            private int coursor = -1;

            //判断是否存在下一个
            public boolean hasNext() {
                return coursor + 1 < size;
            }

            //获取下一个
            public E next() {
                coursor++;
                return (E) elem[coursor];
            }

            //删除下一个
            public void remove() {
                //移动数组元素
                System.arraycopy(elem, coursor + 1, elem, coursor, size - coursor - 1);
                size--;
                //指针回退
                coursor--;
            }
        };
    }

    public static void main(String[] args) {
        IterArrayList<Integer> list = new IterArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        Iterator<Integer> it = list.iterator();
        while(it.hasNext()) {
            System.out.println(it.next());
        }

        IterArrayList list1 = new IterArrayList();
        list1.add("aaa");
        list1.add("bbb");
        list1.add("ccc");
        for(Object str : list1) {
            System.out.println(str);
        }
    }
}

HashMap分拣存储

/**
 * 分拣存储:1:N
 * 统计单词出现的次数
 * this is a cat and that is a mice and where is the food?
 * @author L J
 */
public class WordCountDemo {
    public static void main(String[] args) {
        //分割字符串
        String[] str = "this is a cat and that is a mice and where is the food ?".split(" ");
        Map<String, Integer> map = new HashMap<String, Integer>();
        //分拣存储
        for(int i = 0; i < str.length; i++) {
            /*if(!map.containsKey(str[i])) {
                map.put(str[i], 1);
            }else{
                map.put(str[i], map.get(str[i]) + 1);
            }*/

            Integer value = map.get(str[i]);
            if(null == value) {
                map.put(str[i], 1);
            }else{
                map.put(str[i], map.get(str[i]) + 1);
            }
        }

        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        //按要求查看单词出现的次数
        while(it.hasNext()) {
            String key = it.next();
            Integer value = map.get(key);
            System.out.println(key + "-->" + value);
        }
    }
}

关于javabean的快捷键

public class Letter {
    private String name; //单词
    private int count;   //次数

    //alt+/
    public Letter() {
    }

    //alt+shift+s-->o
    public Letter(String name, int count) {
        super();
        this.name = name;
        this.count = count;
    }

    //alt+shift+s-->r-->tab-->enter-->shift+tab-->enter
    public String getName() {
        return name;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

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

Comparable接口+Comparator接口

public int compareTo(Object obj);
该方法:

  • 返回 0 表示 this == obj
  • 返回正数 表示 this > obj
  • 返回负数 表示 this < obj
    内置类的比较:
/**
 * 排序[冒泡]
 * @author L J
 */
public class SortUtils {
    /**
     * List排序+Comparator接口
     * @param <T>
     * @param list
     * @param com
     */
    public static <T> void sort(List<T> list, Comparator<T> com) {
        //转成数组
        Object[] arr = list.toArray();

        sort(arr, com);
        //改变容器中对应位置的值
        for(int i = 0; i < arr.length; i++) {
            list.set(i, (T) arr[i]);
        }
    }

    /**
     * 数组的排序+Comparator接口
     * @param <T>
     * @param arr
     * @param com
     */
    public static <T> void sort(Object[] arr, Comparator<T> com) {
        boolean sorted = true;
        int len = arr.length;
        for(int i = 0; i < len - 1; i++) {
            sorted = true; //假定有序
            for(int j = 0; j < len - 1 - i; j++) {
                if(com.compare((T)arr[j], (T)arr[j + 1]) > 0) {
                    Object temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    sorted = false; //假定失败
                }
            }
            if(sorted) { //减少趟数
                break;
            }
        }
    }

    /**
     * 容器排序
     */
    public static <T extends Comparable<T>> void sort(List<T> list) {
        //转成数组
        Object[] arr = list.toArray();

        sort(arr);
        //改变容器中对应位置的值
        for(int i = 0; i < arr.length; i++) {
            list.set(i, (T) arr[i]);
        }
    }

    /**
     * 数组排序(使用泛型方法)
     */
    public static <T extends Comparable<T>> void sort(T[] arr) {
        //从小到大排序
        boolean sorted = true;
        int len = arr.length;
        for(int i = 0; i < len - 1; i++) {
            sorted = true; //假定有序
            for(int j = 0; j < len - 1 - i; j++) {
                if(((Comparable) arr[j]).compareTo(arr[j + 1]) > 0) {
                    T temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    sorted = false;  //假定失败
                }
            }
            if(sorted) {
                break;
            }
        }
    }

    /**
     * 数组的排序
     * @param arr
     */
    public static void sort(Object[] arr) {
        //从小到大排序
        boolean sorted = true;
        int len = arr.length;
        for(int i = 0; i < len - 1; i++) {
            sorted = true; //假定有序
            for(int j = 0; j < len - 1 - i; j++) {
                if(((Comparable) arr[j]).compareTo(arr[j + 1]) > 0) {
                    Object temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    sorted = false;  //假定失败
                }
            }
            if(sorted) {
                break;
            }
        }
    }
}

测试类:

/**
 * 内置类的比较+业务类比较
 * @author L J
 *  */
public class SortDemo {
    public static void main(String[] args) {
        Date[] arr = new Date[3];
        arr[0] = new Date();
        arr[1] = new Date(System.currentTimeMillis() - 1000 * 60 * 60);
        arr[2] = new Date(System.currentTimeMillis() + 1000 * 60 * 60);

        SortUtils.sort(arr);
        for(Date d : arr) {
            System.out.println(d);
        }

        //字符串
        String[] arr2 = {"a", "abcd", "abc", "def"};
        SortUtils.sort(arr2);
        System.out.println(Arrays.toString(arr2)); //[a, abc, abcd, def]

        //容器排序
        List<String> list = new ArrayList<String>();
        list.add("a");
        list.add("abcd");
        list.add("abc");
        list.add("def");
        SortUtils.sort(list);
        for(String d : list) {
            System.out.println(d);
        }

        String[] arr3 = new String[]{"a", "abcd", "abc", "def"};
        SortUtils.sort(arr3, new StringComp());
        System.out.println(Arrays.toString(arr3));

        //容器排序+Comparator接口
        list = new ArrayList<String>();
        list.add("a");
        list.add("abcd");
        list.add("abc");
        list.add("def");
        SortUtils.sort(list, new StringComp());
        for(String d : list) {
            System.out.println(d);
        }
    }
}

Collections类中的排序

/**
 * 测试Collections类
 * public static <T> void sort(List<T> list, Comparator<? super T> c)
 * public static <T extends Comparable<? super T>> void sort(List<T> list)
 * @author L J
 */
public class CollectionsTest {
    public static void main(String[] args) {
        //容器排序+Comparator接口
        List list = new ArrayList<String>();
        list.add("a");
        list.add("abcd");
        list.add("abc");
        list.add("def");
        Collections.sort(list, new StringComp());
        System.out.println(list);

        list = new ArrayList<String>();
        list.add("a");
        list.add("abcd");
        list.add("abc");
        list.add("def");
        Collections.sort(list);
        System.out.println(list);
    }
}

TreeSet与TreeMap

TreeSet数据元素可以排序且不可重复

  • 如果元素可以排序 java.lang.Comparable + compareTo,用空参构造器new TreeSet()
public class Worker implements Comparable<Worker>{
    private String type; //工种
    private double salary; //工资

    public Worker() {
    }

    public Worker(String type, double salary) {
        super();
        this.type = type;
        this.salary = salary;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    /**
     * 按工资升序
     * @param o
     * @return
     */
    @Override
    public int compareTo(Worker o) {
        return this.salary > o.salary ? 1 : (this.salary == o.salary ? 0 : -1);
    }

    @Override
    public String toString() {
        return "工种:" + this.type + "工资:" + this.salary + "\n";
    }
}
public class TreeSetDemo2 {
    public static void main(String[] args) {
        Worker w1 = new Worker("垃圾回收员", 12000);
        Worker w2 = new Worker("农民工", 8000);
        Worker w3 = new Worker("程序员", 5000);

        TreeSet<Worker> employees = new TreeSet<Worker>();
        employees.add(w1);
        employees.add(w2);
        employees.add(w3);

        System.out.println(employees);
    }
}
  • 如果要排序业务类 java.util.Comparator+compare,用new TreeSet(Comparator< ? super E> comparator)
public class Person {
    private String name;  //名称
    private int handsome; //帅气指数

    public Person() {
    }

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

    public String getName() {
        return name;
    }

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

    public int getHandsome() {
        return handsome;
    }

    public void setHandsome(int handsome) {
        this.handsome = handsome;
    }

    @Override
    public String toString() {
        return "姓名:" + this.name + " 帅气指数:" + this.handsome + "\n";
    }
}
public class TreeSetDemo {
    public static void main(String[] args) {
        Person p1 = new Person("您", 100);
        Person p2 = new Person("胡歌", 10000);
        Person p3 = new Person("吴奇隆", 1000);
        Person p4 = new Person("张敬轩", 1000);

        //依次存放到TreeSet容器中,使用排序的业务类[匿名内部类]
        TreeSet<Person> persons = new TreeSet<Person>(
            new Comparator<Person>() {
                @Override
                public int compare(Person o1, Person o2) {
                    return o1.getHandsome() - o2.getHandsome();
                }
            }
        );
        persons.add(p1);
        persons.add(p2);
        persons.add(p3);
        persons.add(p4);
        System.out.println(persons);

        //输出和上面一样,说明TreeSet在添加数据时排序
        p4.setHandsome(-100);
        System.out.println(persons);
    }
}

TreeMap要求键可以排序,与TreeSet同理

public class TreeMapDemo2 {
    public static void main(String[] args) {
        Worker w1 = new Worker("垃圾回收员", 12000);
        Worker w2 = new Worker("农民工", 8000);
        Worker w3 = new Worker("程序员", 5000);

        TreeMap<Worker, String> employees = new TreeMap<Worker, String>();
        employees.put(w1, "lj");
        employees.put(w2, "lj");
        employees.put(w3, "lj");

        Set<Worker> set = employees.keySet();
        System.out.println(set);
    }
}
public class TreeMapDemo {
    public static void main(String[] args) {
        Person p1 = new Person("您", 100);
        Person p2 = new Person("胡歌", 10000);
        Person p3 = new Person("吴奇隆", 1000);
        Person p4 = new Person("张敬轩", 1001);

        TreeMap<Person, String> map = new TreeMap<Person, String>(
            new Comparator<Person>() {
                @Override
                public int compare(Person o1, Person o2) {
                    return o1.getHandsome() - o2.getHandsome();
                }
            }
        );
        map.put(p1, "lj");
        map.put(p2, "lj");
        map.put(p3, "lj");
        map.put(p4, "lj");

        //查看键
        Set<Person> persons = map.keySet();
        System.out.println(persons);
    }
}

Collections类应用

public class CollectionsDemo {
    public static void main(String[] args) {
        //test();

        List<Integer> cards = new ArrayList<Integer>();
        //洗牌,模拟斗地主
        for(int i = 0; i < 54; i++) {
            cards.add(i);
        }
        Collections.shuffle(cards);

        List<Integer> person1 = new ArrayList<Integer>();
        List<Integer> person2 = new ArrayList<Integer>();
        List<Integer> person3 = new ArrayList<Integer>();
        List<Integer> last = new ArrayList<Integer>();
        //发牌
        for(int i = 0; i < 51; i+=3) {
            person1.add(cards.get(i));
            person2.add(cards.get(i + 1));
            person3.add(cards.get(i + 2));
        }

        //最后三张是底牌
        last.add(cards.get(51));
        last.add(cards.get(52));
        last.add(cards.get(53));

        System.out.println("第一个人:" + person1);
        System.out.println("第二个人:" + person2);
        System.out.println("第三个人:" + person3);
        System.out.println("底牌是:" + last);
    }

    //反转
    public static void test() {
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        System.out.println(list);
        Collections.reverse(list);
        System.out.println(list );
    }
}

Queue(队列)与Deque(双端队列)

/**
 * 模拟银行业务
 * @author L J
 */
public class QueueDemo {
    public static void main(String[] args) {
        //Queue接口,ArrayDeque类是一个数组双端队列
        Queue<Request> que = new ArrayDeque<Request>();

        //模拟排队情况
        for(int i = 0; i < 10; i++) {
            final int num = i; 
            que.offer(new Request() {
                @Override
                public void dopost() {
                    System.out.println("第" + num + "个人在办理存款业务,存款额度为:" + (Math.random() * 1000));
                }
            });
        }

        dealWith(que);
    }

    //处理业务
    public static void dealWith(Queue<Request> que) {
        Request req = null;
        while(null != (req = que.poll())) {
            req.dopost();
        }
    }
}

interface Request {
    void dopost();
}

自定义栈:

/**
 * 自定义堆栈
 * @author L J
 */
public class MyStack<E> {
    //容器
    private Deque<E> container = new ArrayDeque<E>();

    //容量
    private int cap;

    public MyStack(int cap) {
        super();
        this.cap = cap;
    }

    //压栈
    public boolean push(E e) {
        if(container.size() + 1 > cap) {
            return false;
        }
        return container.offerLast(e);
    }

    //出栈
    public E pop() {
        return container.pollLast();
    }

    //获取
    public E peek() {
        return container.peekLast();
    }

    //获取容器大小
    public int size() {
        return container.size();
    }
}
//测试自定义堆栈
public class MyStackTest {
    public static void main(String[] args) {
        MyStack<String> stack = new MyStack<String>(3);
        stack.push("baidu");
        stack.push("google");
        stack.push("sina");
        stack.push("bjsxt");

        System.out.println("大小:" + stack.size()); //3

        //遍历
        String item = null;
        while(null != (item = stack.pop())) {
            System.out.println(item);
        }
    }
}

Enumeration接口和Vector类

作用和Iterator接口类似

/**
 * Enumeration的使用
 * 1、判断hasMoreElement()
 * 2、获取nextElement()
 * 
 * Vector的elements()方法,返回此向量的组件的枚举
 * @author L J
 */
public class EnumDemo {
    public static void main(String[] args) {
        Vector<String> vector = new Vector<String>();
        vector.add("javase");
        vector.add("html");
        vector.add("oracle");

        //遍历该Vector
        Enumeration<String> en = vector.elements();
        while(en.hasMoreElements()) {
            System.out.println(en.nextElement());
        }
    }
}
/**
 * Enumeration接口的子类
 * StringTokenizer类和String类的split()方法类似
 * 用于字符串的分割
 * StringTokenizer(String str, String delim)
 * @author L J
 */
public class EnumDemo2 {
    public static void main(String[] args) {
        String emailStr = "lj@qq.com;1475077659@qq.com;lijun4@primeton.com";
        StringTokenizer token = new StringTokenizer(emailStr, ";");
        while(token.hasMoreElements()) {
            System.out.println(token.nextElement());
        }
    }
}

HashTable类和Properties类

HashTable和HashMap的区别:

  • HashTable的父类是Dictionary,而HashMap的父类是AbstractMap类
  • HashTable的键和值不能为空,HashMap的键可以有一个为null,值可以为空
  • HashTable是线程安全的,HashMap不是线程安全的

Properties类的作用:

  • 读写资源配置文件
  • 键与值只能为字符串
/**
 *Properties 资源配置文件的读写
 *1、key和value只能为字符串
 *2、存储与读取
 *setProperty(String key, String value)
 *getProperty(String key, String defaultValue) 
 - @author L J 
 */
public class PropertiesDemo {
    public static void main(String[] args) {
        //创建对象
        Properties pro = new Properties();
        //存储
        pro.setProperty("driver", "com.mysql.jdbc.Driver");
        pro.setProperty("url", "jdbc:mysql://localhost:3306/mydb2");
        pro.setProperty("user", "root");
        pro.setProperty("password", "root");

        String url = pro.getProperty("url", "哈哈");
        System.out.println(url);   //jdbc:mysql://localhost:3306/mydb2
    }
}
/**
 - 使用Properties输出到文件
 - @author L J
 */
public class PropertiesDemo2 {
    public static void main(String[] args) throws Exception {
        //创建对象
        Properties pro = new Properties();
        //存储
        pro.setProperty("driver", "com.mysql.jdbc.Driver");
        pro.setProperty("url", "jdbc:mysql://localhost:3306/mydb2");
        pro.setProperty("user", "root");
        pro.setProperty("password", "root");

        //存储到F:\DB\Properties(绝对路径)
        pro.store(new FileOutputStream(new File("F:/DB/Properties/db.properties")), "mysql数据库配置");
        pro.storeToXML(new FileOutputStream(new File("F:/DB/Properties/db.xml")), "mysql数据库配置");

        //使用相对路径
        pro.store(new FileOutputStream(new File("src/com/belief/template/basic/db.properties")), "mysql数据库配置");
    }
}
/**
 - 使用Properties读取配置文件
 - @author L J
 */
public class PropertiesDemo3 {
    public static void main(String[] args) throws Exception {
        Properties pro = new Properties();
        //读取 绝对路径
        pro.load(new FileReader("F:/DB/properties/db.properties"));
        System.out.println(pro.getProperty("user", "root"));

        //读取 相对路径(相对整个工程)
        pro.load(new FileReader("src/com/belief/template/basic/db.properties"));
        System.out.println(pro.getProperty("url", "root"));

        //类相对路径  /表示根目录bin
        pro.load(PropertiesDemo3.class.getResourceAsStream("/com/belief/template/basic/db.properties"));
        System.out.println(pro.getProperty("driver", "root"));

        //""表示根目录bin
        pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("com/belief/template/basic/db.properties"));
        System.out.println(pro.getProperty("driver", "root"));
    }
}

引用分类

  • 强引用(StrongReference):引用指向对象,gc( Garbage collection)运行时不回收
  • 软引用(SoftReference):运行时可能回收(jvm内存不够时回收)
  • 弱引用(WeakReference):gc运行时立即回收
  • 虚引用(PhantomReference):类似于无引用,主要跟踪对象被回收的状态,不能单独使用,必须与引用队列联合使用

WeakHashMap,IdentityHashMap和EnumMap

/**
 * WeakHashMap键为弱类型,gc运行立即回收
 * @author L J
 */
public class WeakHashMapDemo {
    public static void main(String[] args) {
        WeakHashMap<String, String> map = new WeakHashMap<String, String>();
        //常量池对象,不会回收
        map.put("abc", "a");
        map.put("bcd", "b");
        //gc运行,被回收
        map.put(new String("abc"), "a");
        map.put(new String("bcd"), "a");

        //通知回收
        System.gc();
        System.runFinalization();

        System.out.println(map.size()); //2
    }
}
/**
 * IdentityHashMap键比较地址去重
 * @author L J
 */
public class IdentityHashMapDemo {
    public static void main(String[] args) {
        IdentityHashMap<String, String> map = new IdentityHashMap<String, String>();
        //常量池,地址相同
        map.put("a", "a1");
        map.put("a", "a2");

        map.put(new String("a"), "a3");
        map.put(new String("a"), "a4");
        System.out.println(map.size()); //3
    }
}
/**
 * EnumMap键必须为枚举类型
 * public EnumMap(Class<K> keyType)
 * keyType --> 此枚举映射的键类型的 class对象 
 * @author L J
 */
public class EnumMapDemo {
    public static void main(String[] args) {

        EnumMap<Season, String> map = new EnumMap<Season, String>(Season.class);
        //存放值
        map.put(Season.SPRING, "春天");
        map.put(Season.SUMMER, "夏天");
        map.put(Season.AUTUMN, "秋天");
        map.put(Season.WINTER, "冬天");
        System.out.println(map.size()); //4
    }
}

//季节枚举类
enum Season {
    SPRING,SUMMER,AUTUMN,WINTER
}

集合的同步控制与只读设置

Collections类提供了synchronizedXxx()方法,将指定容器包装成同步

  • synchronizedList()
  • synchronizedSet()
  • synchronizedMap()
/**
 * 只读设置
 * emptyXxx() 空的不可变的集合
 * 1、emptyList() 
 * 2、emptyMap() 
 * 3、emptySet() 
 * singletonXxx() 一个元素不可变的集合
 * 1、singleton(T o)  返回一个只包含指定对象的不可变 set
 * 2、singletonList(T o)
 * 3、singletonMap(K key, V value)
 * unmodifiableXxx() 不可变容器
 * 1、unmodifiableList(List<? extends T> list) 
 * 2、unmodifiableMap(Map<? extends K,? extends V> m) 
 * 3、unmodifiableSet(Set<? extends T> s) 
 * @author L J
 */
public class ReadonlyDemo {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("a", "a1");
        map.put("b", "b1");
        //只读控制
        Map<String, String> map2 = Collections.unmodifiableMap(map);
        //map2.put("c", "c1");
        System.out.println(map2.size());

        //一个元素的容器测试
        List<String> list = Collections.singletonList(new String("aaa"));
        //list.add("test");
        System.out.println(list.get(0)); //aaa
    }

    public static Set<String> operate(Set<String> set) {
        if(null == set) {
            return Collections.emptySet(); //避免NullPointerException
        }
        return set;
    }
}

guava包(对集合的扩展)

guava包由Google公司开发

/**
 * Guava只读设置
 * Guava包来自google公司
 * @author L J
 */
public class GuavaDemo {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("c");
        //对原有的List进行包装,相当于原有List的一个视图,不够安全
        List<String> readList = Collections.unmodifiableList(list);
        //readList.add("d");
        //
        list.add("d"); //改变原有的List,视图也一起改变
        System.out.println(list.get(3));  //d

        //Guava的只读设置安全可靠,相对简单
        List<String> immutableList = ImmutableList.of("a", "b", "c");
        immutableList.add("d");
    }
}
/**
 * 函数式编程
 * Predicate 断言
 * Function 函数
 * 匿名内部类的使用
 * @author L J 
 */
public class GuavaDemo2 {
    public static void main(String[] args) {
        //组合式函数编程
        //确保容器中的字符串长度不超过5,超过进行截取后全部大写
        List<String> list = Lists.newArrayList("bjsxt", "good", "happiness");

        //截取字符串
        Function<String, String> f1 = new Function<String, String>() {
            @Override
            public String apply(String input) {
                return input.length() > 5 ? input.substring(0, 5) : input;
            }
        };

        //转成大写
        Function<String, String> f2 = new Function<String, String>() {
            @Override
            public String apply(String input) {
                return input.toUpperCase();
            }
        };

        //String = f2(f1(String))
        Function<String, String> f = Functions.compose(f1, f2);
        Collection<String> resultCol = Collections2.transform(list, f);

        for(String temp : resultCol) {
            System.out.println(temp);
        }
    }

    //转换 
    public static void function() {
        //类型转换
        Set<Long> timeSet = Sets.newHashSet();
        timeSet.add(10000000L);
        timeSet.add(999999999999999L);
        timeSet.add(20000000000L);

        //将Set中的Long类型数转换成日期格式的字符串
        Collection<String> timeStrCol = Collections2.transform(timeSet, new Function<Long, String>() {
            @Override
            public String apply(Long input) {
                //业务逻辑
                return new SimpleDateFormat("yyyy-MM-dd").format(input);
            }
        });

        for(String temp : timeStrCol) {
            System.out.println(temp);
        }
    }

    //过滤
    public static void filter() {
        //创建List,静态初始化
        List<String> list = Lists.newArrayList("moom", "son", "refer", "dad", "bjsxt");

        //找出回文串(palindrome)
        //匿名内部类对象
        Collection<String> palindromeList = Collections2.filter(list, new Predicate<String>() {
            @Override
            public boolean apply(String input) {
                //业务逻辑
                return new StringBuilder(input).reverse().toString().equals(input);
            }
        });

        for(String temp : palindromeList) {
            System.out.println(temp);
        }
    }
}
/**
 * 加入约束条件:非空、长度验证
 * Constraint
 * 匿名内部类的使用
 * @author L J
 */
public class GuavaDemo3 {
    public static void main(String[] args) {
        Set<String> sets = Sets.newHashSet();
        //创建约束
        Constraint<String> constraint = new Constraint<String>() {
            @Override
            public String checkElement(String element) {
                //非空验证
                Preconditions.checkNotNull(element);
                //长度验证
                Preconditions.checkArgument(element.length() >=5 && element.length() <= 20);

                return element;
            }
        };

        Set<String> cs = Constraints.constrainedSet(sets, constraint);
        //java.lang.NullPointerException
        //cs.add(null); 
        //java.lang.IllegalArgumentException
        //cs.add("aaaa");
        cs.add("aaaaa");

        for(String temp : cs) {
            System.out.println(temp); //aaaaa
        }
    }
}
/**
 * 集合的操作:交集、差集、并集
 * @author L J
 */
public class GuavaDemo4 {
    public static void main(String[] args) {
        Set<Integer> sets = Sets.newHashSet(1,2,3,4,5,6);
        Set<Integer> sets2 = Sets.newHashSet(4,5,6,7,8,9);

        //交集
        System.out.println("交集为:");
        SetView<Integer> intersection = Sets.intersection(sets, sets2);
        for(Integer temp : intersection) {
            System.out.print(temp + " ");
        }

        //差集
        System.out.println();
        System.out.println("差集为:");
        SetView<Integer> diff = Sets.difference(sets, sets2);
        for(Integer temp : diff) {
            System.out.print(temp + " ");
        }

        //并集
        System.out.println();
        System.out.println("并集为:");
        SetView<Integer> union = Sets.union(sets, sets2);
        for(Integer temp : union) {
            System.out.print(temp + " ");
        }
    }
}

guava之Multiset、Multimap、BiMap

/**
 * 统计单词出现的次数
 * 1、HashMap 分拣存储
 * 2、MultiSet 无序+可重复
 * @author L J
 */
public class GuavaDemo5 {
    public static void main(String[] args) {
        String str = "this is a cat and that is a mice where is the food";
        String[] strArray = str.split(" ");
        //存储到MuitiSet中
        Multiset<String> set = HashMultiset.create();

        for(String temp : strArray) {
            set.add(temp);
        }

        //获取所有的单词Set,不可重复
        Set<String> letters = set.elementSet();
        for(String temp : letters) {
            System.out.println(temp + "-->" + set.count(temp));
        }
    }
}
/**
 * Multimap key可以重复
 * @author L J
 */
public class GuavaDemo6 {
    public static void main(String[] args) {
        Map<String, String> course = new HashMap<String, String>();
        //加入数据
        course.put("改革开放", "邓爷爷");
        course.put("三个代表", "江主席");
        course.put("科学发展观", "胡主席");
        course.put("和谐社会", "胡主席");
        course.put("八荣八耻", "胡主席");

        //Multimap
        Multimap<String, String> teachers = ArrayListMultimap.create();

        //迭代器
        Iterator<Entry<String, String>> it = course.entrySet().iterator();
        while(it.hasNext()) {
            Entry<String, String> entry = it.next();
            String key = entry.getKey();  //课程
            String value = entry.getValue();  //教师

            //教师-->课程
            teachers.put(value, key);
        }

        //查看Multimap
        Set<String> keyset = teachers.keySet();
        for(String key : keyset) {
            Collection<String> col = teachers.get(key);
            System.out.println(key + "-->" + col);
        }
    }
}
/**
 * HashMap 键唯一,值可以重复
 * BiMap 双向Map,键与值都不能重复
 * @author L J
 */
public class GuavaDemo7 {
    public static void main(String[] args) {
        BiMap<String, String> bimap = HashBiMap.create();
        bimap.put("bjsxt", "bjsxt@sina.com");
        bimap.put("good", "good@qq.com");
        //通过邮箱找用户,inverse()方法将键值对调
        String user = bimap.inverse().get("bjsxt@sina.com");
        System.out.println(user); //bjsxt
    }
}

guava之双键的Map:Table

/**
 * 课程/学生  A  B  C
 * javase 90 80 60
 * html5  68 89 78
 * python 92 88 99
 * 
 * 双键的Map-->Table-->rowKey+columnKey+value
 * 1、方法
 * 所有的行数据:cellSet()
 * 所有的学生:rowKeySet()
 * 所有的课程:columnKeySet()
 * 所有的成绩:values()]
 * 学生对应的课程:rowMap()+get(学生)
 *            row(学生)
 * 课程对应的学生:columnMap+get(课程)
 *            column(课程)
 * @author L J
 */
public class GuavaDemo8 {
    public static void main(String[] args) {
        Table<String, String, Integer> table = HashBasedTable.create();
        //测试数据
        table.put("A", "javase", 90);
        table.put("A", "html5", 68);
        table.put("A", "python", 92);
        table.put("B", "javase", 80);
        table.put("B", "html5", 89);
        table.put("B", "python", 88);
        table.put("C", "javase", 60);
        table.put("C", "html5", 78);
        table.put("C", "python", 99);

        //所有的行数据
        Set<Cell<String, String, Integer>> cells = table.cellSet();
        for(Cell<String, String, Integer> temp : cells) {
            System.out.println(temp.getRowKey() + "-->" + temp.getColumnKey() + "-->" + temp.getValue());
        }

        System.out.println("=============================");
        System.out.print("课程/学生\t");
        //获取所有的学生
        Set<String> stu = table.rowKeySet();
        for(String s : stu) {
            System.out.print(s + "\t");
        }

        System.out.println();

        //获取所有的课程
        Set<String> course = table.columnKeySet();
        for(String c : course) {
            System.out.print(c + "\t");
            //得到:学生-->分数的Map
            Map<String, Integer> score = table.column(c);
            for(String s : stu) {
                System.out.print(score.get(s) + "\t");
            }
            System.out.println();
        }

        System.out.println("=============================");

        //将键进行互换
        Table<String, String, Integer> table2 = Tables.transpose(table);
        //所有的行数据
        Set<Cell<String, String, Integer>> cells2 = table2.cellSet();
        for(Cell<String, String, Integer> temp : cells2) {
            System.out.println(temp.getRowKey() + "-->" + temp.getColumnKey() + "-->" + temp.getValue());
        }
    }
}

commons包(对集合的扩展)

commons包由Apache组织开发
Predicate:

/**
 * 函数式编程之Predicate 断言(理解为判别式,就是if...else的替代)
 * @author L J
 */
public class CommonsDemo {
    public static void main(String[] args) {
        //自定义的判别式
        Predicate<String> selfPre = new Predicate<String>() {
            @Override
            public boolean evaluate(String input) {
                return input.length() >= 5 && input.length() <= 20;
            }
        };
        //非空判断
        Predicate notNull = NotNullPredicate.notNullPredicate();

        //PredicateUtils类有allPredicate()方法,形参为多个参数
        //andPredicate()方法有两个参数(两个参数要都为真,类似逻辑与)
        //anyPredicate()方法可以有多个参数(参数有一个为真即可,类似逻辑或)
        Predicate all = PredicateUtils.allPredicate(selfPre, notNull);

        List<String> list = PredicatedList.predicatedList(new ArrayList<String>(), all);
        //list.add("3456");
        list.add("bjsxt");
        //list.add(null);
    }

    //唯一判断
    public static void unique() {
        Predicate<Long> uniquePre = UniquePredicate.uniquePredicate();
        List<Long> list = PredicatedList.predicatedList(new ArrayList<Long>(), uniquePre);
        list.add(100L);
        list.add(200L);
        //出现重复值,出现异常
        //list.add(100L);
    }

    //非空判断
    public static void notNull() {
        //两种方式创建实例
        //Predicate notNull = NotNullPredicate.INSTANCE;
        Predicate notNull = NotNullPredicate.notNullPredicate();
        String str = "a";
        System.out.println(notNull.evaluate(str)); //非空为true,否则为false

        //添加容器时值的判断
        List<Long> list = PredicatedList.predicatedList(new ArrayList<Long>(), notNull);
        list.add(1000L);
        //出现异常
        //list.add(null);
    }

    //相等判断
    public static void equal() {
        //两种方式创建实例
        //Predicate<String> pre = new EqualPredicate<String>("bjsxt");
        Predicate<String> pre = EqualPredicate.equalPredicate("bjsxt");
        boolean flag = pre.evaluate("bjs");
        System.out.println(flag);     //false
    }
}

Transformer:

//雇员类
public class Employee {
    private String name;  //姓名
    private double salary;  //工资
    public Employee() {
    }
    public Employee(String name, double salary) {
        super();
        this.name = name;
        this.salary = salary;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "(姓名:"+ this.name + " 薪水:" + this.salary + ")";
    }
}
//等级类
public class Level {
    private String name;  //姓名
    private String level;  //薪资水平
    public Level() {
    }
    public Level(String name, String level) {
        super();
        this.name = name;
        this.level = level;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getLevel() {
        return level;
    }
    public void setLevel(String level) {
        this.level = level;
    }

    @Override
    public String toString() {
        return "(姓名:"+ this.name + " 薪资水平:" + this.level + ")";
    }
}
/**
 * 函数式编程Transformer 类型转化
 * @author L J
 */
public class CommonsDemo2 {
    public static void main(String[] args) {
        //判别式
        Predicate<Employee> isLow = new Predicate<Employee>() {
            @Override
            public boolean evaluate(Employee emp) {
                return emp.getSalary() < 10000;
            }
        };

        Predicate<Employee> isHigh = new Predicate<Employee>() {
            @Override
            public boolean evaluate(Employee emp) {
                return emp.getSalary() >= 10000;
            }
        };

        Predicate[] pres = {isLow, isHigh};

        //转换
        Transformer<Employee, Level> lowTrans = new Transformer<Employee, Level>() {
            @Override
            public Level transform(Employee input) {
                return new Level(input.getName(), "初级程序员");
            }
        };

        Transformer<Employee, Level> highTrans = new Transformer<Employee, Level>() {
            @Override
            public Level transform(Employee input) {
                return new Level(input.getName(), "高级程序员");
            }
        };

        Transformer[] trans = {lowTrans, highTrans};

        //关联
        Transformer switchTrans = new SwitchTransformer(pres, trans, null);

        List<Employee> list = new ArrayList<Employee>();
        list.add(new Employee("小明", 20000));
        list.add(new Employee("小张", 2000));
        list.add(new Employee("小黑", 200));

        //自定义类型的转换
        Collection<Level> level = CollectionUtils.collect(list, switchTrans);

        for(Level temp : level) {
            System.out.println(temp);
        }
    }

    //内置类型的转换,将长整形的日期转换成指定格式的字符串
    public static void inner() {
        Transformer<Long, String> trans = new Transformer<Long, String>(){
            @Override
            public String transform(Long input) {
                return new SimpleDateFormat("yyyy年MM月dd日").format(input);
            }
        };

        List<Long> list = new ArrayList<Long>();
        list.add(11111111L);
        list.add(3000000000000L);

        //CollectionUtils类的collect方法将集合和转换器结合起来
        Collection<String> result = CollectionUtils.collect(list, trans);
        for(String temp : result) {
            System.out.println(temp);
        }
    }
}

闭包(Closure)

/**
 * 函数式编程closure 闭包(封装特定的业务功能)
 * @author L J
 */
public class CommonsDemo3 {
    public static void main(String[] args) {
        //basic();
        //ifClosure();
        //whileClosure();
        chainedClosure();
    }

    //如果是打折商品,先进行9折,然后满百再减20
    public static void chainedClosure() {
        List<Goods> goodsList = new ArrayList<Goods>();
        goodsList.add(new Goods("java", 150.0, true));
        goodsList.add(new Goods("CSS3", 100.0, false));
        goodsList.add(new Goods("HTML5", 120.0, false));

        //业务:满100减20
        Closure<Goods> subtract = new Closure<Goods>() {
            @Override
            public void execute(Goods goods) {
                goods.setPrice(goods.getPrice() >= 100 ? goods.getPrice() - 20 : goods.getPrice());
            }
        };

        //业务:打9折
        Closure<Goods> discount = new Closure<Goods>() {
            @Override
            public void execute(Goods goods) {
                if(goods.isDiscount()) {
                    goods.setPrice(goods.getPrice() * 0.9);
                }
            }
        };

        //先打折,再满百减20
        Closure<Goods> chainedClo = ChainedClosure.chainedClosure(discount, subtract);

        CollectionUtils.forAllDo(goodsList, chainedClo);

        for(Goods goods : goodsList) {
            System.out.println(goods);
        }
    }

    //确保所有的员工工资都大于10000,如果已经超过的不再上涨
    public static void whileClosure() {
        List<Employee> empList = new ArrayList<Employee>();
        empList.add(new Employee("bjsxt", 10000));
        empList.add(new Employee("is", 1000));
        empList.add(new Employee("good", 5000));

        //业务功能
        Closure<Employee> clos = new Closure<Employee>() {
            @Override
            public void execute(Employee emp) {
                emp.setSalary(emp.getSalary() * 1.2);
            }
        };

        //判断
        Predicate<Employee> empPre = new Predicate<Employee>() {
            @Override
            public boolean evaluate(Employee emp) {
                return emp.getSalary() < 10000;
            }
        };

        //false:执行while循环  true:执行do...while循环
        Closure<Employee> whileClo = WhileClosure.whileClosure(empPre, clos, false);

        //工具类
        CollectionUtils.forAllDo(empList, whileClo);

        //操作后的数据
        Iterator<Employee> empIt = empList.iterator();
        while(empIt.hasNext()) {
            System.out.println(empIt.next());
        }
    }

    //如果是打折商品,进行9折,否则满百减20
    public static void ifClosure() {
        List<Goods> goodsList = new ArrayList<Goods>();
        goodsList.add(new Goods("java", 150.0, true));
        goodsList.add(new Goods("CSS3", 100.0, false));
        goodsList.add(new Goods("HTML5", 120.0, false));

        //业务:满100减20
        Closure<Goods> subtract = new Closure<Goods>() {
            @Override
            public void execute(Goods goods) {
                goods.setPrice(goods.getPrice() >= 100 ? goods.getPrice() - 20 : goods.getPrice());
            }
        };

        //业务:打9折
        Closure<Goods> discount = new Closure<Goods>() {
            @Override
            public void execute(Goods goods) {
                if(goods.isDiscount()) {
                    goods.setPrice(goods.getPrice() * 0.9);
                }
            }
        };

        //判断
        Predicate<Goods> pre = new Predicate<Goods>() {
            @Override
            public boolean evaluate(Goods goods) {
                return goods.isDiscount();
            }
        };

        //业务二选一:ifClosure(判断, true时业务, false时业务);
        Closure<Goods> ifClo = IfClosure.ifClosure(pre, discount, subtract);

        CollectionUtils.forAllDo(goodsList, ifClo);

        for(Goods goods : goodsList) {
            System.out.println(goods);
        }
    }

    //闭包基本操作(全部工资上涨0.2)
    public static void basic() {
        List<Employee> empList = new ArrayList<Employee>();
        empList.add(new Employee("bjsxt", 10000));
        empList.add(new Employee("is", 1000));
        empList.add(new Employee("good", 5000));

        //业务功能
        Closure<Employee> clos = new Closure<Employee>() {
            @Override
            public void execute(Employee emp) {
                emp.setSalary(emp.getSalary() * 1.2);
            }
        };

        //工具类
        CollectionUtils.forAllDo(empList, clos);

        //操作后的数据
        Iterator<Employee> empIt = empList.iterator();
        while(empIt.hasNext()) {
            System.out.println(empIt.next());
        }
    }
}

commons之集合与队列

/**
 * 集合操作
 * 1、并集
 * 2、交集
 * 3、差集
 * @author L J
 */
public class CommonsDemo4 {
    public static void main(String[] args) {
        Set<Integer> set1 = new HashSet<Integer>();
        set1.add(1);
        set1.add(2);
        set1.add(3);
        set1.add(4);

        Set<Integer> set2 = new HashSet<Integer>();
        set2.add(3);
        set2.add(4);
        set2.add(5);
        set2.add(6);

        //并集
        Collection<Integer> col = CollectionUtils.union(set1, set2);
        for(Integer temp : col) {
            System.out.println(temp);
        }

        System.out.println("================");

        //交集
        //col = CollectionUtils.intersection(set1, set2);
        col = CollectionUtils.retainAll(set1, set2);
        for(Integer temp : col) {
            System.out.println(temp);
        }

        System.out.println("================");

        //差集
        col = CollectionUtils.subtract(set1, set2);
        for(Integer temp : col) {
            System.out.println(temp);
        }
    }
}
/**
 * 1、循环队列
 * 2、只读队列
 * 3、断言队列
 * @author L J
 */
public class CommonsDemo5 {
    public static void main(String[] args) {
        //ircular();
        //readOnly();
        predicate();
    }

    //断言队列
    public static void predicate() {
        CircularFifoQueue<String> que = new CircularFifoQueue<String>(2);
        que.add("a");
        que.add("b");
        que.add("c");

        Predicate notNull = NotNullPredicate.INSTANCE;
        //包装成对应的队列
        Queue<String> que2 = PredicatedQueue.predicatedQueue(que, notNull);
        que2.add(null);
    }

    //只读队列
    public static void readOnly() {
        CircularFifoQueue<String> que = new CircularFifoQueue<String>(2);
        que.add("a");
        que.add("b");
        que.add("c");

        //将que封装成只读队列
        Queue<String> readOnlyQue = UnmodifiableQueue.unmodifiableQueue(que);
        readOnlyQue.add("d");
    }

    //循环队列
    public static void circular() {
        //先进先出,本队列里面只保留两个元素
        CircularFifoQueue<String> que = new CircularFifoQueue<String>(2);
        que.add("a");
        que.add("b");
        que.add("c");

        //查看
        for(int i = 0; i < que.size(); i++) {
            System.out.println(que.get(i));
        }
    }
}

commons对集合迭代器的扩展

/**
 * 迭代器的扩展
 * 1、MapIterator Map迭代器
 * 2、UniqueFilterIterator 去重迭代器
 * 3、FilterIterator 自定义迭代器
 * 4、LoopingIterator 循环迭代器
 * 5、ArrayListIterator 数组迭代器
 * @author L J
 */
public class CommonsDemo6 {
    public static void main(String[] args) {
        //mapIt();
        //uniqueIt();
        //filter();
        //loopIt();
        arrayIt();
    }

    //数组迭代器
    public static void arrayIt() {
        int[] arr = {1, 2, 3, 4, 5};
        Iterator<Integer> it = new ArrayListIterator<Integer>(arr);
        while(it.hasNext()) {
            System.out.println(it.next());
        }
    }

    //循环迭代器
    public static void loopIt() {
        List<String> list = new ArrayList<String>();
        list.add("refer");
        list.add("dad");
        list.add("bjsxt");
        list.add("moom");

        Iterator<String> it = new LoopingIterator<String>(list);
        //想循环多少次循环多少次
        for(int i = 0; i < 6; i++) {
            System.out.println(it.next());
        }
    }

    //自定义迭代器
    public static void filter() {
        List<String> list = new ArrayList<String>();
        list.add("refer");
        list.add("dad");
        list.add("bjsxt");
        list.add("moom");

        //自定义条件判断
        Predicate<String> pre = new Predicate<String>(){
            @Override
            public boolean evaluate(String input) {
                //回文判断
                return new StringBuilder(input).reverse().toString().equals(input);
            }
        };

        Iterator<String> it = new FilterIterator<String>(list.iterator(), pre);
        while(it.hasNext()) {
            System.out.println(it.next());
        }
    }

    //去重迭代器
    public static void uniqueIt() {
        List<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("a");
        list.add("d");
        Iterator<String> it = new UniqueFilterIterator<String>(list.iterator());
        while(it.hasNext()) {
            System.out.println(it.next());
        }
    }

    //Map迭代器
    public static void mapIt() {
        IterableMap<String, String> map = new HashedMap<String, String>();
        map.put("a", "bjsxt");
        map.put("b", "sxt");
        map.put("c", "good");

        //使用MapIterator
        MapIterator<String, String> it = map.mapIterator();

        while(it.hasNext()) {
            String key = it.next();
            String value = it.getValue();
            System.out.println(key + "-->" + value);
        }
    }
}

commons之BidiMap

/**
 * 双向Map 要求键与值都不能重复
 * BidiMap
 * 1、DualTreeBidiMap : 有序
 * 2、DualHashBidiMap : 无序
 * @author L J
 */
public class CommonsDemo7 {
    public static void main(String[] args) {
        //hashMap();
        //treeMap();
    }

    //有序的双向Map
    public static void treeMap() {
        BidiMap<String, String> map = new DualTreeBidiMap<String, String>();
        map.put("bj", "bj@qq.com");
        map.put("sxt", "sxt@qq.com");

        //反转
        System.out.println(map.inverseBidiMap().get("bj@qq.com"));

        //遍历查看
        MapIterator<String, String> it = map.inverseBidiMap().mapIterator();
        while(it.hasNext()) {
            String key = it.next();
            String value = it.getValue();
            System.out.println(key + "-->" + value);
        }
    }

    //无序的双向Map
    public static void hashMap() {
        BidiMap<String, String> map = new DualHashBidiMap<String, String>();
        map.put("bj", "bj@qq.com");
        map.put("sxt", "sxt@qq.com");

        //反转
        System.out.println(map.inverseBidiMap().get("bj@qq.com"));

        //遍历查看
        MapIterator<String, String> it = map.inverseBidiMap().mapIterator();
        while(it.hasNext()) {
            String key = it.next();
            String value = it.getValue();
            System.out.println(key + "-->" + value);
        }
    }
}

commons之Bag

/**
 * Bag 包(允许重复)
 * 1、HashBag 无序
 * 2、TreeBag 有序
 * 统计单词出现的次数
 * @author L J
 */
public class CommonsDemo8 {
    public static void main(String[] args) {
        //hashBag();
        //treeBag();
        String str = "this is a cat and that is a mice where is the food";
        //分割字符串
        String[] strArray = str.split(" ");
        Bag<String> bag = new TreeBag<String>();

        for(String temp : strArray) {
            bag.add(temp);
        }

        Set<String> keys = bag.uniqueSet();
        for(String letter : keys) {
            System.out.println(letter + "-->" + bag.getCount(letter));
        }
    }

    //有序的包
    public static void treeBag() {
        Bag<String> bag = new TreeBag<String>();
        bag.add("a");
        bag.add("a", 5);
        bag.remove("a", 2);
        bag.add("b");
        bag.add("c");

        //迭代
        Iterator<String> it = bag.iterator();
        while(it.hasNext()) {
            System.out.println(it.next());
        }
    }

    //无序的包
    public static void hashBag() {
        Bag<String> bag = new HashBag<String>();
        bag.add("a");
        bag.add("a", 5);
        bag.remove("a", 2);
        bag.add("b");

        //迭代
        Iterator<String> it = bag.iterator();
        while(it.hasNext()) {
            System.out.println(it.next());
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值