透析Java本质-集合类的使用及性能分析

集合类-继承关系图





一.ArrayList 2 LinkedList性能分析

package com.java.essence_36;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.*;

/**
 * Created by lw on 14-5-20.
 * 
 * 运行内存-Xms512m -Xmx512m -XX:+PrintGCDetails
 */
public class ArrayList2LinkedList_Compare {


    private static final int INIT_SIZE = 500000;
    private static final int ADDRANDOM_SIZE = 10000;

    public static LinkedList<Object> linkedList = new LinkedList();
    public static ArrayList<Object> arrayList = new ArrayList(INIT_SIZE);
    private static Object object = new Object();
    private static Random random = new Random();


    public void add2Last(String state, List list) {
        for (int i = 0; i < INIT_SIZE; i++) {
            list.add(object);
        }
    }

    public void add2Random(String state, List list) {
        int temp = 0;
        for (int i = 0; i < ADDRANDOM_SIZE; i++) {
            temp = random.nextInt(INIT_SIZE);
            list.add(temp, object);
        }
    }

    public void remove2Random(String state, List list) {
        int temp = 0;
        for (int i = 0; i < ADDRANDOM_SIZE; i++) {
            temp = random.nextInt(INIT_SIZE);
            list.remove(temp);
        }
    }

    public void forEach2(String state, List list) {

        for (Object o : list) {
            object = o;
        }
    }


    public void iterator2(String state, List list) {
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            object = iterator.next();
        }
    }

    public void for2(String state, List list) {
        for (int i = 0; i < INIT_SIZE; i++) {
            object = list.get(i);
        }
    }

    public static void main(String[] args) {
        Proxy_Cglib proxy_cglib = new Proxy_Cglib();
        ArrayList2LinkedList_Compare compare =
                (ArrayList2LinkedList_Compare) proxy_cglib.getInstance(new ArrayList2LinkedList_Compare());
        compare.add2Last("ArrayList  末尾添加数据[50w次]测试:", arrayList);
        compare.add2Last("LinkedList 末尾添加数据[50w次]测试:", linkedList);

        System.out.println();
        compare.add2Random("ArrayList  随机位置添加数据[1w次]测试:", arrayList);
        compare.add2Random("LinkedList 随机位置添加数据[1w次]测试:", linkedList);

        System.out.println();
        compare.remove2Random("ArrayList  随机位置删除次数[1w次]测试:", arrayList);
        compare.remove2Random("LinkedList 随机位置删除次数[1w次]测试:", linkedList);

        System.out.println();
        compare.forEach2("ArrayList  forEach2循环读取测试:", arrayList);
        compare.forEach2("LinkedList forEach2循环读取测试:", linkedList);

        System.out.println();
        compare.iterator2("ArrayList  iterator2循环读取测试:", arrayList);
        compare.iterator2("LinkedList iterator2循环读取测试:", linkedList);

        System.out.println();
        compare.for2("ArrayList  for循环读取测试:", arrayList);
        compare.for2("LinkedList for循环读取测试:", linkedList);

    }
}


/**
 * Created by lw on 14-5-1.
 * <p/>
 * cglib动态代理
 * 项目中计时方法执行计时使用
 */
class Proxy_Cglib implements MethodInterceptor {

    private Object object;

    /**
     * 创建代理对象
     *
     * @param object
     * @return
     */
    public Object getInstance(Object object) {
        this.object = object;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.object.getClass());
        // 回调方法
        enhancer.setCallback(this);
        // 创建代理对象
        return enhancer.create();
    }

    @Override
    // 回调方法
    public Object intercept(Object obj, Method method, Object[] args,
                            MethodProxy proxy) throws Throwable {
        long start = System.currentTimeMillis();
        proxy.invokeSuper(obj, args);
        System.out.println(args[0] + "执行耗时:" + (System.currentTimeMillis() - start) + "ms");
        return null;
    }
}


执行结果分析

 
 * 运行内存-Xms512m -Xmx512m -XX:+PrintGCDetails
 * 测试的结果与实际两者的区别不符,ArrayList居然任何地方表现优秀
 * !!!待追究原因...
 * 
 * ------------------------------------------------
 * ArrayList  末尾添加数据[50w次]测试:执行耗时:8ms
 * LinkedList 末尾添加数据[50w次]测试:执行耗时:15ms
 * Q:
 * ArrayList如果没有指定大小会动态扩展,涉及到数组的复制
 * ------------------------------------------------
 * 
 * ------------------------------------------------
 * ArrayList  随机位置添加数据[1w次]测试:执行耗时:516ms
 * LinkedList 随机位置添加数据[1w次]测试:执行耗时:3104ms
 * Q:
 * ArrayList每次随机插入时候进行一次数组的复制
 * 表现应该没有LinkedList优秀
 * ------------------------------------------------
 * 
 *  ------------------------------------------------
 * ArrayList  随机位置删除次数[1w次]测试:执行耗时:508ms
 * LinkedList 随机位置删除次数[1w次]测试:执行耗时:3621ms
 * Q:
 * ArrayList 每次删除一个元素时候将进行数组的复制,引用下标-1
 *  因此越靠前开销越大
 * LinkedList删除时候判断位置是{前半段、中间、后半段}去删除
 * ArrayList应该没有LinkedList优秀
 *  ------------------------------------------------
 * 
 *  ------------------------------------------------
 * ArrayList  forEach2循环读取测试:执行耗时:10ms
 * LinkedList forEach2循环读取测试:执行耗时:23ms
 * 
 * ArrayList  iterator2循环读取测试:执行耗时:9ms
 * LinkedList iterator2循环读取测试:执行耗时:29ms
 * 
 * ArrayList  for循环读取测试:执行耗时:6ms
 * LinkedList for循环读取测试: 无穷大...
 * Q:
 *  随机访问ArrayList优秀
 *  ------------------------------------------------

二.有序的HashMap -LinkedHashMap


package com.java.essence_36;

import java.util.*;

/**
 * Created by lw on 14-5-20.
 * <p/>
 * 有序的HashMap -LinkedHashMap
 */
public class Linked_HashMap {

    private static Map<Integer, String> integerStringMap;

    /**
     * accessOrder=true  按照元素最后访问时间排序
     * accessOrder=false 按照元素添加顺序排序
     * public LinkedHashMap(int initialCapacity,float loadFactor,boolean accessOrder) {
     * ..
     * }
     */
    private static void InitLinked_HashMap(boolean accessOrder) {
        integerStringMap = new LinkedHashMap(16, 0.75f, accessOrder);
        integerStringMap.put(1, "a");
        integerStringMap.put(2, "b");
        integerStringMap.put(3, "c");
        integerStringMap.put(4, "d");

        System.out.println("访问key=2、3的元素....");
        integerStringMap.get(2);
        integerStringMap.get(3);

        System.out.println(integerStringMap);
    }

    /**
     * accessOrder=true  按照元素最后访问时间排序
     * 遍历时候由Key获取Value时候抛出java.util.ConcurrentModificationException
     * <p/>
     * 遍历时候,LinkedHashMap调用get方法会修改LinkedHashMap结构。
     * remove亦是。
     * 参考下面is2ConcurrentModificationException()方法内容
     */
    private static void for_Linked_HashMap() {
        integerStringMap = new LinkedHashMap(16, 0.75f, true);
        integerStringMap.put(1, "a");
        integerStringMap.put(2, "b");
        integerStringMap.put(3, "c");
        integerStringMap.put(4, "d");
        Set<Integer> set = integerStringMap.keySet();
        for (Integer integer : set) {
            integerStringMap.get(integer);
            // integerStringMap.remove(integer);
        }
    }

    public static void main(String[] args) {
        InitLinked_HashMap(true);
        InitLinked_HashMap(false);

        //for_Linked_HashMap();
        is2ConcurrentModificationException();
    }

    /**
     * 衍生:List怎么移除元素?
     *      forEach怎么执行的呢?
     * 什么时候产生快速失败?什么时候产生安全失败?
     */
    private static void is2ConcurrentModificationException() {
        String str;
        List<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");

        for (String s : list) {
            //list.remove(s);
        }

        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            str = iterator.next();
            //list.remove(str);
        }

        Map map = new HashMap();
        map.put(1, "a");
        map.put(2, "b");

        for (int i = 0; i < map.size(); i++) {
            //  map.remove(1);
        }

        Set<Integer> set = map.keySet();
        for (Integer integer : set) {
            //set.remove(integer);//yes
            //map.remove(integer);//yes
        }

    }
}


三.实现了排序的 TreeMap

package com.java.essence_36;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by lw on 14-5-20.
 * 学生姓名与成绩
 */
class Student implements Comparable<Student> {

    String name;
    int score;

    /**
     * 衍生疑问:
     * 为什么要有构造器?
     * 他做了什么?
     * 对象到底是谁创建的?构造器里面吗?
     * this到底什么?
     */
    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }

    /**
     * 重写排序实现方法
     * 按成绩比较
     *
     * @param o
     * @return
     */
    @Override
    public int compareTo(Student o) {
        if (o.score > this.score) {
            return -1;
        }
        if (o.score < this.score) {
            return 1;
        }

        return 0;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", score=" + score +
                '}';
    }
}

//学生的详细信息
class Student_Message {
    String address;

    Student_Message(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "address='" + address;
    }
}

public class Tree_Map {

    //①:比较的对象实现了Comparable接口
    private static Map<Student, Student_Message> map = new TreeMap();

    //①:将Comparator 传入构造器
    private static Map<Student, Student_Message> map_1 = new TreeMap(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            return 0;
        }

        @Override
        public boolean equals(Object obj) {
            return false;
        }
    });
    /**
     * 衍生疑问:
     * 以上2种方法有什么区别。
     * 为什么Comparator还需要重写equals方法?
     */

    /**
     * 初始化treeMap
     */
    private static void InitTreeMap() {
        Student yiwa = new Student("yiwa", 20);
        Student erwa = new Student("erwa", 30);
        Student sanwa = new Student("sanwa", 40);
        Student siwa = new Student("siwa", 80);
        Student wuwa = new Student("wuwa", 100);
        map.put(yiwa, new Student_Message("TY"));
        map.put(erwa, new Student_Message("TY"));
        map.put(sanwa, new Student_Message("TY"));
        map.put(siwa, new Student_Message("TY"));
        map.put(wuwa, new Student_Message("TY"));

        //查询一娃~~四娃成绩之间的学生
        System.out.println(((TreeMap) map).subMap(yiwa, siwa));
        System.out.println();
        //查询成绩大于一娃的学生
        System.out.println(((TreeMap) map).tailMap(yiwa));
        System.out.println();
        //查询成绩小于三娃的学生
        System.out.println(((TreeMap) map).headMap(sanwa));
    }

    public static void main(String[] args) {
        InitTreeMap();
    }
}

四 .HashSet、LinkedSet、TreeSet的不同

package com.java.essence_36;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;

/**
 * Created by lw on 14-5-20.
 */
public class Set_ {

    private static Set<Integer> set;

    private static void initSet2Type(Set<Integer> set1, String state) {
        set = set1;
        set.add(3);
        set.add(5);
        set.add(130);
        set.add(13);
        set.add(33);
        System.out.println("\n\nSet->Type:" + state);
        for (Integer integer : set) {
            System.out.print(integer + "\t");
        }
    }

    public static void main(String[] args) {
        initSet2Type(new HashSet(), "new HashSet()");

        initSet2Type(new LinkedHashSet(), "new LinkedHashSet()");

        initSet2Type(new TreeSet(), "new TreeSet()");
    } 

}

打印输出
 /*  打印
        Set->Type:new HashSet()
        33	130	3	5	13

        Set->Type:new LinkedHashSet()
        3	5	130	13	33

        Set->Type:new TreeSet()
        3	5	13	33	130
        */


你可能感兴趣的:(性能,object,Class,ArrayList,LinkedList)