◎ add
새로운 객체를 저장한다
HashSet<String>set = new HashSet<>();
set.add("A");
System.out.println(set);
◎ addAll(Collection c)
주어진 컬렉션에 저장된 모든 객체들을 추가한다.
HashSet<String>set = new HashSet<>();
set.add("A");
ArrayList<String>list = new ArrayList<>();
list.add("철수");
list.add("영희");
list.add("민수");
list.add("철수");
list.add("민수");
set.addAll(list);
System.out.println(set);//[A, 철수, 민수, 영희]
◎ clear
저장된 모든 객체를 삭제한다
HashSet<String>set = new HashSet<>();
set.add("A");
System.out.println(set);//[A]
set.clear();
System.out.println(set);//[]
◎ clone
HashSet을 복제해서 반환한다.(얕은 복사)
HashSet<String>set = new HashSet<>();
set.add("A");
System.out.println(set);//[A]
HashSet<String>set2= (HashSet<String>) set.clone();
System.out.println(set2);//[A]
◎ contains(Object o) / containsAll(Collection c)
지정된 객체를 포함하고 있는지 알려준다. / 주어진 컬렉션에 저장된 모든 객체를 포함하고 있는지 알려준다.
HashSet<String>set = new HashSet<>();
set.add("A");
set.add("B");
set.add("E");
set.add("C");
set.add("D");
System.out.println(set.contains("C"));//true
ArrayList<String>list = new ArrayList<>();
list.add("A");
list.add("E");
System.out.println(set.containsAll(list));//true
list.add("H");
System.out.println(set.containsAll(list));//false
◎ isEmpty
HashSet이 비어있는지 알려준다.
HashSet<String>set = new HashSet<>();
set.add("A");
System.out.println(set);//[A]
set.clear();
System.out.println(set.isEmpty);//true
◎ remove(Object o) / removeAll(Collection c)
지정된 객체를 HashSet에서 삭제한다.(성공하면 true 실패하면 false) / 주어진 컬렉션에서 저장된 모든 객체와 동일한 것들을 HashSet에서 모두 삭제한다.
HashSet<String>set = new HashSet<>();
set.add("A");
set.add("B");
set.add("E");
set.add("C");
set.add("D");
set.remove("D");
System.out.println(set);//[A, B, C, E]
ArrayList<String>list = new ArrayList<>();
list.add("A");
list.add("E");
list.add("H");
set.removeAll(list);
System.out.println(set);//[B, C]
◎ retainAll(Collection c)
주어진 컬렉션에 저장된 객체와 동일한 것만 남기고 삭제한다.
HashSet<String>set = new HashSet<>();
set.add("A");
set.add("B");
set.add("E");
set.add("C");
set.add("D");
System.out.println(set);//[A, B, C, D, E]
ArrayList<String>list = new ArrayList<>();
list.add("A");
list.add("E");
list.add("H");
set.retainAll(list);
System.out.println(set);//[A, E]
◎ size
저장된 객체의 개수를 반환
HashSet<String>set = new HashSet<>();
set.add("A");
set.add("B");
set.add("E");
set.add("C");
set.add("D");
System.out.println(set.size());//5
◎ toArray
저장된 객체들을 객체배열의 형태로 반환
HashSet<String>set = new HashSet<>();
set.add("A");
set.add("B");
set.add("E");
set.add("C");
set.add("D");
String[] str = set.toArray(new String[set.size()]);
for (String tmp:str) {
System.out.print(tmp);
}//ABCDE
'개발 지식 기록 > JAVA' 카테고리의 다른 글
[메서드 정리] LinkedList (0) | 2023.08.18 |
---|---|
[메서드 정리] HashMap (0) | 2023.08.18 |
[메서드 정리] ArrayList (0) | 2023.08.13 |
[메서드 정리] StringBuffer & StringBuilder (0) | 2023.08.13 |
[자바의 정석] 개인적인 정리글 (2주차) (0) | 2023.08.06 |