Java self - the difference between the set framework HashSet, LinkedHashSet, TreeSet

The difference between HashSet, LinkedHashSet, TreeSet

步骤 1 : HashSet LinkedHashSet TreeSet

HashSet: disordered
LinkedHashSet: insertion order
TreeSet: from small to large

package collection;
  
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.TreeSet;
  
public class TestCollection {
    public static void main(String[] args) {
        HashSet<Integer> numberSet1 =new HashSet<Integer>();
        //HashSet中的数据不是按照插入顺序存放
        numberSet1.add(88);
        numberSet1.add(8);
        numberSet1.add(888);
          
        System.out.println(numberSet1);
          
        LinkedHashSet<Integer> numberSet2 =new LinkedHashSet<Integer>();
        //LinkedHashSet中的数据是按照插入顺序存放
        numberSet2.add(88);
        numberSet2.add(8);
        numberSet2.add(888);
          
        System.out.println(numberSet2);
        TreeSet<Integer> numberSet3 =new TreeSet<Integer>();
        //TreeSet 中的数据是进行了排序的
        numberSet3.add(88);
        numberSet3.add(8);
        numberSet3.add(888);
          
        System.out.println(numberSet3);
          
    }
}

Exercise : neither repeat, another order

LinkedHashSet neither repeated use, but also the characteristics of the sequence, the digital Math.PI, printed in order of appearance, the same numerals, only occurs once

The answer :
Here Insert Picture Description

package collection;
 
import java.util.LinkedHashSet;
import java.util.Set;
 
public class TestCollection {
    public static void main(String[] args) {
        Set<Integer> result = new LinkedHashSet<>();
        String str = String.valueOf(Math.PI);
        // 去掉点
        str = str.replace(".", "");
        char[] cs = str.toCharArray();
        for (char c : cs) {
            int num = Integer.parseInt(String.valueOf(c));
            result.add(num);
        }
        System.out.printf("%s中的无重复数字是:%n",String.valueOf(Math.PI));
        System.out.println(result);
 
    }
}

Guess you like

Origin www.cnblogs.com/jeddzd/p/12141668.html