Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

공부일지

ArrayList, hashMap 사용법 본문

Java

ArrayList, hashMap 사용법

알라알리야 2023. 3. 8. 00:28

ArrayList 선언 방법

ArrayList<String> a = new ArrayList<>();
ArrayList<String> a1 = new ArrayList<>(Arrays.asList("a","b","c")); //요소가 있는 ArrayList
ArrayList<Integer> b = new ArrayList<>();

 

ArrayList 객체 추가, 객체 검색, 객체 삭제

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

/* 객체 추가 */
a.add("A");
a.add("B");

/* 객체 검색 */
a.get(0); // "A"

/* 객체 삭제 */
a.remove(0); // "A" 삭제, "B"만 출력

 

 

HashMap 객체 선언, 객체 추가, 객체 검색, 객체 삭제

HashMap<String, Integer> a = new HashMap<>();
HashMap<String, Integer> a1 = new HashMap<>(10); // 초기 용량 지정
HashMap<String, Integer> a2 = new HashMap<>(a); // a의 모든 값을 가진 HashMap생성


/* 객체 추가 */
a.put("홍길동", 1);
a.put("아무개", 2);

/* 객체 검색 */
a.get("홍길동"); // 1 출력
a.get("아무개"); // 2 출력

/* 객체 삭제 */
a.remove("홍길동"); // Key와 Key의 Value인 Entry 삭제

 

 

HashMap 순회하는 3가지 방법

 

1. ketSet을 이용

HashMap<String, Integer> a = new HashMap<>();
a.put("홍길동", 1);
a.put("아무개", 2);

Set<String> aKeySet = a.keySet();
Iterator<String> aKeySetIt = aKeySet.iterator();

while(aKeySetIt.hasNext()) {
	String x = aKeySetIt.next(); // Key 값을 x에 저장
	Integer y = a.get(x); // Key가 x인 Values 값을 y에 저장
	System.out.println(x + "," + y); // 홍길동,1 \n 아무개,2 출력
}

 

 

2. entrySet을 이용

HashMap<String, Integer> a = new HashMap<>();
a.put("홍길동", 1);
a.put("아무개", 2);

Set<Map.Entry<String, Integer>> aEntrySet = a.entrySet(); // HashMap a를 Set으로 변경
Iterator<Map.Entry<String, Integer>> aEntrySetIt = aEntrySet.Iterator(); // Iterator 생성

while(aEntrySetIt.hasNaxt()) {
	Map.Entry<String, Integer> entry = aEntrySetIt.Next(); // 객체의 Key와 Value를 entry에 저장
	String x = entry.getKey(); // Key값을 x에 저장
	Integer y = entry.getValue(); // Value값을 y에 저장
	System.out.println(x + "," + y); // 홍길동,1 \n 아무개,2 출력
}

 

 

3. values 이용

HashMap<String, Integer> a = new HashMap<>();
a.put("홍길동", 1);
a.put("아무개", 2);

Collection<Integer> aValues = a.values(); // HashMap a의 모든 value 값을 aValues에 저장
Iterator<Integer> aValuesIt = aValues.iterator(); // iterator 생성

while(aValuesIt.hasNext()) {
	Integer x = aValuesIt.next(); // a의 Value를 x에 저장
	System.out.println(x); // 출력 1 \n 2
}
Comments