Code&Data Insights

[ 기초수학| JAVA ] - 집합 < Set - HashSet / ArrayList > 본문

Computer Science/Comp sci_courses

[ 기초수학| JAVA ] - 집합 < Set - HashSet / ArrayList >

paka_corn 2022. 5. 24. 08:44

 

< 집합 (set) >

 

자바에서 집합을  사용하기 위한 방법에는

대표적으로 HashSet과 ArrayList를 사용하는 것이 있다.

 

 

 

1. HashSet 

- 자바에서 Hashset 클래스는 저장을 위한 해시 테이블을 생성하기 위해 사용된다

( Java HashSet class is used to create a collection that uses a hash table for storage.)

 

- 추상클래스인 AbstractSet class를 상속하고 Set interface를 implements 한다. 

 

- HashSet은 Set의 파생클래스로, Set은 중복된 원소를 허용하지 않는 집합이다. 

* HashSet은 순서,중복을 고려하지 X 

 

 

 

 

(1) 집합 사용하기 - HashSet 

 

// import java.util.HashSet;

System.out.println("[ HashSet ]");
HashSet set1 = new HashSet();

set1.add(1);
set1.add(1); // 중복 허용 X 

set1.add(2);
set1.add(3); // set = {1,2,3}

set1.remove(1); //set = {2,3}

System.out.println(set1.size());  // size:2
System.out.println(set1.contains(2)); // true


System.out.println("[ Intersection : 교집합 ]");
HashSet a = new HashSet(Arrays.asList(1,2,3,4,5);
HashSet b = new HashSet(Arrays.asList(2,4,6,8,10,12);
a.retainAll(b); // 2,4


System.out.println("[ Sum of Sets : 합집합]");
a.addAll(b); //1,2,3,4,5,6,8,10,12

 
System.out.println("[ Difference of Sets : 차집합]");
a.removeAll(b); // A - B : 1,3,5

 

 

 

2. ArrayList

- array와의 가장 큰 차이점은 배열(array)는 사이즈를 선언 후 수정할수 없지만, 

ArrayList는 추가, 삭제등 수정이 자유롭다. 

 

- ArrayList는 동적인 크기의 원소의 집단을 저장하기 위해 사용한다.

(ArrayList in Java is used to store a dynamically sized collection of elements.)

 

- 자바 컬렉션 프레임워크의 한 부분으로, 자바 List 인터페이스를 구현한다.

(ArrayList is part of Java's collection framework and implements Java's List interface.)

 

 

 

 

(1) 집합 구현하기 - ArrayList

 

// import java.util.ArrayList;

ArrayList<Integer> list;

MySet()
{
	this.list = new ArrayList<Integer>();
}

MySet(int[] arr)
{
	this.list = new ArrayList<Integer>();
    
    for(int item:arr)
    {
    	this.list.add(item);
    }
}

//add elements without duplicates
public void add(int x)
{
	for(int item:this.list)
    {	
    	// 같은 원소가 이미 존재한다면 추가 하지 않고 리턴 (중복값 허용X)
    	if(item==x)
        {
        	return;
        }
    }
    
    this.list.add(x);
}

System.out.println("[ Intersection : 교집합 ]");
public MySet retainAll(Myset b)
{
	MySet result = new MySet();
    
    for(int itemA: this.list)
    {
    	for(int itemB:b.list)
        {
        	if(itemA == itemB)
            {
            	result.add(itemA);
            }
        }	
    }
	
    return result; // 교집합 
}


System.out.println("[ Sum of Sets : 합집합]");
public MySet addAll(Myset b)
{
	MySet result = new MySet();
    
    for(int itemA: this.list)
    {
    	result.add(itemA);
    }
	
    for(int itemB:b.list)
    {
    	result.add(itemB);
    }
	
    return result; // 합집합 - 위에서 정의한 add()함수에서 중복을 허용하지 않기 때문에 원소만 더하면 합집합이 출력됨 
}
 
 
System.out.println("[ Difference of Sets : 차집합]");
public MySet removeAll(MySet b)
{
	MySet result = new MySet();
    
    for(int itemA:this.list)
    {
    	boolean containFlag = false;
        
        for(int itemB: b.list)
        {
        	if(itemA == itemB)
            {
            	containFlag = true;
                break;
            }
        }
        
        if(!containFlag) // containFlag = false면 if(!containFlag) = true가 되어 if문 실행.
        {
        	result.add(itemA);
        }
    }
	
    return result; // 차집합 
}

 

 

Comments