1. 程式人生 > 其它 >java實現十大排序演算法

java實現十大排序演算法

java8 JDK

一、Set集合


(1)、Set子介面

  • 特點:無序、無下標、元素不可重複。
  • 方法:全部繼承自Collection中的方法。

(2)、Set實現類

  • HashSet【重點】:
    • 基於HashCode實現元素不重複
    • 當存入元素的雜湊碼相同時,會呼叫equals進行確認,如結果為true,則拒絕後者存入。
  • TreeSet:
    • 基於排列順序實現元素不重複。
    • 實現了SortedSet介面,對集合元素自動排序。
    • 元素物件的型別必須實現Comparable介面,指定排序規則。
    • 通過CompareTo方法確定是否為重複元素。
Set介面的使用
package qfClass.generic;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * 測試Set介面的使用
 * 特點:(1)無序、沒有下標(2)不能重複
 **/
public class Demo02 {
    public static void main(String[] args) {
        //建立集合
        Set<String> set = new HashSet<>();
        //1. 新增資料
        set.add("蘋果");
        set.add("華為");
        set.add("小米");
        set.add("小米");
        System.out.println("資料個數:"+set.size()); //資料個數:3
        System.out.println(set.toString()); //[蘋果, 華為, 小米]

        //2. 刪除資料
        set.remove("小米");
        System.out.println(set.toString()); //[蘋果, 華為]

        //3. 遍歷【重點】
        //3.1 使用增強for
        System.out.println("----增強for----");
        for (String string : set) {
            System.out.println(string);// 蘋果 華為
        }
        //3.2 使用迭代器
        System.out.println("----使用迭代器----");
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());// 蘋果 華為
        }

        //4. 判斷
        System.out.println(set.contains("華為"));
        System.out.println(set.isEmpty());
    }
}
HashSet的使用
import java.util.HashSet;
import java.util.Iterator;

/**
 * HashSet的集合的使用
 * 儲存結構:雜湊表(陣列+連結串列+紅黑樹)
 **/
public class Demo03 {
    public static void main(String[] args) {
        //建立集合
        HashSet<String> hashSet = new HashSet<>();
        //1. 新增元素
        hashSet.add("劉德華");
        hashSet.add("梁朝偉");
        hashSet.add("周潤發");
        hashSet.add("林志玲");
        hashSet.add("劉德華");
        System.out.println("元素個數:"+hashSet.size()); //元素個數:4
        System.out.println(hashSet.toString()); //[林志玲, 梁朝偉, 周潤發, 劉德華]

        //2. 刪除資料
        //hashSet.remove("劉德華");
        //System.out.println("刪除之後:"+hashSet.size());

        //3. 遍歷操作
        //3.1 增強for
        System.out.println("----3.1 增強for----");
        for (String string : hashSet) {
            System.out.println(string);
        }
        //3.2 使用迭代器
        System.out.println("----3.2 迭代器----");
        Iterator<String> it = hashSet.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }

        //4. 判斷
        System.out.println(hashSet.contains("郭富城")); //false
        System.out.println(hashSet.isEmpty()); //false
    }
}