JAVA基本数据结构

名称底层结构线性安全有序性值唯一性
Vector数组安全
HashTable数组+链表安全不为空,唯一
LinkedList双向链表不安全
ArrayList数组不安全
HashSet数组+链表不安全唯一
TreeSet红黑树不安全唯一
HashMap数组+链表/红黑树不安全
TreeMap红黑树不安全
ConcurrentHashMap数组+链表/红黑树安全

1、HashTable 测试


Hashtable<String, String> hashTable = new Hashtable();
hashTable.put("1", "A");
hashTable.put("2", "B");
hashTable.put("1", "C");

Iterator<String> iterator = hashTable.keySet().iterator();
while(iterator.hasNext()){
    String key = (String) iterator.next();
    String value = hashTable.get(key);
    System.out.println("hashTable>>>"+key+" "+value);
}

测试结果:相同key值会覆盖

hashTable>>>2 B
hashTable>>>1 C

2、LinkedList 测试


    List<String> linkedList = new LinkedList<>();
    linkedList.add("A");
    linkedList.add("A");
    linkedList.add("C");
    for(String val : linkedList){
        System.out.println("LinkedList value>>>" + val);
    }

测试结果:值不唯一

LinkedList value>>>A
LinkedList value>>>A
LinkedList value>>>C

3、ArrayList 测试


ArrayList arrayList = new ArrayList();
arrayList.add(0, "A");
arrayList.add(1, "A");
arrayList.add(2, "B");
arrayList.add(3, "C");

for(int i = 0; i < arrayList.size(); i++ ){
    System.out.println("ArrayList >>> " + arrayList.get(i));
}

测试结果:key唯一,值不唯一

ArrayList >>> A
ArrayList >>> A
ArrayList >>> B
ArrayList >>> C

4、HashSet 测试


Set hashSet = new HashSet<>();
hashSet.add("A");
hashSet.add("A");
hashSet.add("B");
Iterator iter = hashSet.iterator();
while (iter.hasNext()){
    System.out.println("HashSet value>>>" + iter.next());
}

测试结果:值唯一

HashSet value>>>A
HashSet value>>>B

5、HashMap 测试


HashMap<String, String> hashMap = new HashMap();
hashMap.put("1", "A");
hashMap.put("2", "B");
hashMap.put("3", "C");
hashMap.put("4", "C");
for(Map.Entry<String, String> entry : hashMap.entrySet()){
    System.out.println("hashMap>>>" + entry.getKey() + "=" + entry.getValue());
}

测试结果:key唯一,值不唯一

hashMap>>>1=A
hashMap>>>2=B
hashMap>>>3=C
hashMap>>>4=C

This entry was posted in 应用. Bookmark the permalink.

发表评论