개발세발

[Java/자바] Collections Framework 본문

코딩공부/Java

[Java/자바] Collections Framework

뉼👩🏻‍💻 2022. 2. 8. 16:57
728x90
반응형
SMALL

Collections Framework

 

 

http://prashantgaurav1.files.wordpress.com/2013/12/java-util-collection.gif

 

🔹 인터페이스  : collection , set, list 

 

collection 과 set은 동일한 api를 제공한다 

클래스 : hashset, arraylist 

배열이 가진 한계인 배열을 만들어 줄 때 배열 크기를 한정적으로 설정해줘야 한다는 점을 극복하기 위한 수단 

 


 

 

🔸 [ArrayList]

Collections Framework 안에 들어가 있는 기능 중 하나이다.

배열과 비슷한 기능을 수행하며, 배열과 달리 배열의 크기를 설정하지 않아도 된다. 

사용 시 java.util.ArrayList 패키지를 import 해줘야 사용 가능하다.

 

ArrayList<String> a1 = new ArrayList<String>();

a1.add("빨강"); //add는 어떤 타입도 받을 수 있음 - 그래서 인자의 데이터 타입은 object
a1.add("파랑");
a1.add("초록");
a1.add("노랑");

for (int i = 0; i<a1.size() ; i++){  //배열값 열거 
    //String value = a1.get(i);   → 인자가 object이므로 String으로 바로 넣을 수 없음 
   // String value = (String) a1.get(i) → 이처럼 형변환 해줘도 되나 제너릭 사용권장
    System.out.println(a1.get(i));
}

 

 

 

  중복값 순서 보장
list O O
set X X

 

 


 

 

🔸 [Set] → 집합

◼️ 집합은 중복값이 존재하지 않는 것을 전제로 한다. 따라서 set 역시 중복값 x 

 

◼️ A.containsAll(B)  : A set 안에 B set 의 전체가 담겨있느냐 ? -> false/true

   : containsAll ; 부분집합

 

◼️ A.addAll(B) : A set 안에 B set 을 합친다 

   : addAll ; 합집합(union)

 

◼️ A.retain(B) : A set 에도 있고 B set 에도 있는 값 

   : retain: 교집합

 

◼️ A.removeAll(B) : A set에서 B set의 값을 빼주는 것 

   ; removeAll ; 차집합 

 

◻️  get / set 과 같은 순서(index) 존재하지 않음

 

 


 

 

🔸 [iterator] : 반복자 

 

interface iteratior <E>

 

◼️ cotain에 담긴 것을 하나하나 꺼내서 하나하나씩의 행동을 하게 해주는 것.

 

 

◼️ iterator 의 Method

 

- hashNext()

- next()

HashSet<Integer> A = new HashSet<Integer>();
//Collection<Integer> A = new HashSet<Integer>();   
//ArrayList<Integer> A = new ArrayList<Integer>();   
A.add(1);
A.add(2);
A.add(3);

Iterator hi = A.iterator(); 
while(hi.hasNext()){  // hi 에 들어간 값을 실행하는 것으로 끝나면 반복문 종료
	System.out.println(hi.next());
    }
}

✔️ hashset, arraylist 둘 다 collection 인터페이스를 구현하고 있고 collecion인터페이스를 구현하고 있는 모든 클래스는 iterator라는 method를 통해서 반복자를 제공하도록 강제되어 있기 때문에 

 

HashSet<Integer> A = new HashSet<Integer>();
ArrayList<Integer> A = new ArrayList<Integer>();   
Collection<Integer> A = new HashSet<Integer>();   

가 똑같은 값을 출력함 

 

- remove()

 

 

 


 

 

🔸 [Map] 함수  ( y = f(x) )

 

 

 

 

◼️ <key, value> 이 주어지며 두 값이 짝지어져서 사용 

◼️ key 값은 중복될 수 없으나 value값은 중복 허용

 

HashMap<String, Integer> a = new HashMap<String, Integer>();
a.put("one", 1);
a.put("two", 2);
a.put("three", 3);
a.put("four", 4);
System.out.println(a.get("one"));
System.out.println(a.get("two"));
System.out.println(a.get("three"));

iteratorUsingForEach(a);
iteratorUsingIterator(a);
728x90
반응형