import java.util.Arrays;
public class ArraySet {
private int capacity;
private Integer[] array;
private int size;
public ArraySet(int capacity) {
this.capacity = capacity;
this.array = new Integer[capacity];
this.size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == capacity;
}
@Override
public String toString() {
return Arrays.toString(Arrays.copyOf(array, size));
}
public boolean contains(Integer e) {
for (int i=0;i<size;i++){
if(array[i].equals(e)){
return true;
}
}
// 아래와 같이 한 줄로도 가능
// return Arrays.asList(array).subList(0, size).contains(e);
return false;
}
public void insert(Integer e) {
if (!contains(e) && !isFull()) {
array[size] = e;
size++;
}
}
public void delete(Integer e) {
for (int i=0;i<size;i++){
if(array[i].equals(e)){
array[i]=array[size-1];
array[size-1]=null;
size--;
break;
}
}
}
public ArraySet union(ArraySet setB){
ArraySet setC=new ArraySet(capacity+setB.capacity);
for(int i=0;i<size;i++){
setC.insert(array[i]);
}
for(int i=0;i<setB.size;i++){
if(!setC.contains(setB.array[i])){
setC.insert(setB.array[i]);
}
}
return setC;
}
public ArraySet intersect(ArraySet setB){
ArraySet setC =new ArraySet(capacity);
for(int i=0;i<size;i++){
if(setB.contains(array[i])){
setC.insert(array[i]);
}
}
return setC;
}
public ArraySet difference(ArraySet setB){
ArraySet setC= new ArraySet(capacity);
for(int i=0;i<size;i++){
if(!setB.contains(array[i])){
setC.insert(array[i]);
}
}
return setC;
}
public static void main(String[] args){
ArraySet A=new ArraySet(10);
ArraySet B=new ArraySet(10);
A.insert(1);A.insert(2);A.insert(3);A.insert(4);A.insert(5);
B. insert (3 ); B. insert (4 ); B. insert (5 ); B. insert (6 ); B. insert (7 );
System.out.println("집합 A: "+A.toString());
System.out.println("집합 B: "+ B.toString());
System.out.println(" 2 ∈ A: "+A.contains(2));
System.out.println(" A ∪ B : "+A.union(B).toString());
System.out.println(" A ∩ B : "+A.intersect(B).toString());
System.out.println(" A - B : "+A.difference(B).toString());
System.out.println("집합 A에서 3 삭제");
A.delete(3);
System.out.println("집합 A: "+A.toString());
}
}
Created by 송바래
✉ gihun3645@naver.com
🚩경기도, 성남시