자바 자기 - 컬렉션 프레임 워크의 ArrayList와 HashSet의 차이

자바의 ArrayList와 HashSet의 차이

예 1 : 시퀀스가 있습니까

ArrayList와 순차
HashSet의를 : 아니오 순서

HashSet의 특정 순서가도 신청서이며,도 해시의 순서이다.

다음은 HasetSet 소스 부분 주석

/**
 * It makes no guarantees as to the iteration order of the set;
 * in particular, it does not guarantee that the order will remain constant over time.
*/

반복 순서는 보장되지 세트 오히려 다른 조건에서 요소의 순서 가능성이 다를 수 있습니다

즉, 동일한 HashSet의 0-9에 삽입되어,보기 위해 JVM의 다른 버전이 동일하지 않다. 개발 때, 일정에 의존 할 수없는 투기의 순서 , 순서 자체는 불안정
이 순서는

package collection;
   
import java.util.ArrayList;
import java.util.HashSet;
    
public class TestCollection {
    public static void main(String[] args) {
           
        ArrayList<Integer> numberList =new ArrayList<Integer>();
        //List中的数据按照插入顺序存放
        System.out.println("----------List----------");
        System.out.println("向List 中插入 9 5 1");
        numberList.add(9);
        numberList.add(5);
        numberList.add(1);
        System.out.println("List 按照顺序存放数据:");
        System.out.println(numberList);
        System.out.println("----------Set----------");
        HashSet<Integer> numberSet =new HashSet<Integer>();
        System.out.println("向Set 中插入9 5 1");
        //Set中的数据不是按照插入顺序存放
        numberSet.add(9);
        numberSet.add(5);
        numberSet.add(1);
        System.out.println("Set 不是按照顺序存放数据:");
        System.out.println(numberSet);
           
    }
}

예 2 : 반복 할 수 있습니다

데이터 목록은 복제 할 수 있습니다
설정 반복 할 수없는 데이터
: 있습니다 반복 기준을
우선 검토 해시 코드와 동일한
데이터를 다른 그 다음, 해시 코드와 다른 경우
해시 같은, 동등한 비교하면 동일한 데이터, 같은 동일한 경우, 그렇지 않으면, 다른 데이터
당신은 반복 할 수 있습니다

package collection;
   
import java.util.ArrayList;
import java.util.HashSet;
    
public class TestCollection {
    public static void main(String[] args) {
           
        ArrayList<Integer> numberList =new ArrayList<Integer>();
        //List中的数据可以重复
        System.out.println("----------List----------");
        System.out.println("向List 中插入 9 9");
        numberList.add(9);
        numberList.add(9);
        System.out.println("List 中出现两个9:");
        System.out.println(numberList);
        System.out.println("----------Set----------");
        HashSet<Integer> numberSet =new HashSet<Integer>();
        System.out.println("向Set 中插入9 9");
        //Set中的数据不能重复
        numberSet.add(9);
        numberSet.add(9);
        System.out.println("Set 中只会保留一个9:");
        System.out.println(numberSet);
           
    }
}

운동 : 임의의 숫자를 반복되지 않는

0 9999 50 사이의 임의의 숫자를 생성, 요구 사항은 복제 할 수 없습니다

답변 :

package collection;
 
import java.util.HashSet;
import java.util.Set;
 
public class TestCollection {
    public static void main(String[] args) {
        Set<Integer> numbers =new HashSet<>();
        while(numbers.size()<50){
            int i = (int) (Math.random()*10000);
            numbers.add(i);
        }
        System.out.println("得到50个不重复随机数:");
        System.out.println(numbers);
    }
}

추천

출처www.cnblogs.com/jeddzd/p/12112663.html