본문 바로가기

Programming language/Java

Java - 8 [Wrapper Class, ArrayList, HashMap]

Wrapper Class

- Wrapper Class는 기본적으로 기본형 자료형에 해당 자료형의 객체를 씌우는 것이다.

- 기본형 자료형을 참조형 자료형 처럼 써야 할때 사용한다.

 

Integer i = new Integer(123);
Integer i = 23;

- 이렇게 생성자로도 선언이 가능하고 기본 자료형처럼도 선언이 가능하다.

System.out.println(123 == 123);
System.out.println(Integer(123).equals(Integer(123));

- 기본형 자료형은 == 연산자가 괜찮으나 참조형으로 변한이상 객체가 되어 .equals() 메소드로 비교해야한다.

 

ArrayList

- 배열과는 다르게 미리 배열의 범위를 지정하지 않아도 된다.

- ArrayList에는 기본형을 넣을수 없다.

ArrayList list = new ArrayList();//타입 미설정 Object로 선언된다.
ArrayList<Student> members = new ArrayList<Student>();//타입설정 Student객체만 사용가능
ArrayList<Integer> num = new ArrayList<Integer>();//타입설정 int타입만 사용가능
ArrayList<Integer> num2 = new ArrayList<>();//new에서 타입 파라미터 생략가능
ArrayList<Integer> num3 = new ArrayList<Integer>(10);//초기 용량(capacity)지정
ArrayList<Integer> list2 = new ArrayList<Integer>(Arrays.asList(1,2,3));//생성시 값추가
ArrayList <Integer> intList = new ArrayList<>();        
//삽입:추가(값)
intList.add(1);
//삭제(index) 해당 값 이후의 index들이 모두 하나씩 당겨진다
intList.remove(3);
// 사이즈(길이)
intList.size();
// 값 출력(index)
intList.get(3);
// 값 검색 : 값이 리스트에 있는지 검색하고 있으면 true 아니면 false 반환
intList.contains(1)
// 값 검색(index) : 값이 리스트에 있는지 검색하고 있으면 true 아니면 false 반환
intList.indexOf(2)
// 모든 값을 제거
intList.clear();

HashMap

- key와 value를 짝으로 이루어진 Array리스트라고 하면 될것이다.

자료형 객체가 key와 value의 짝으로 이루어진 ArrayList인데 key를 넣으면 value로 연결되는 특성을

가진다. 즉, key를 통해 value 값을 숨기거나 연결시켜 사용한다.

 

- key는 hashcode라고 하는 것으로 관리된다. hashcode는 모든 인스턴스를 구분하는 고유값인데 이값이 인스턴스 마다 다르므로 HashMap은 이러한 hashcode로 key를 구분한다. (hashcode가 같은 인스턴스도 존재한다)

 

그런데 String은 문자열이 같으면 같은 hashcode를 갖는다. 따라서 HashMap의 key로 String이 적합하다.

 

HashMap<String, Pokemon> pokedex = new HashMap<>();

key와 value순으로 입력하며 위 코드에서 key는 String, value는 Pokemon이다.

 

// 값추가 .put(key, value)
pokedex.put("피카츄", new Pokemon("피카츄"));
// 값출력 .get(key)
pokedex.get("피카츄");
// 원소수정 .put(key, new_value)
pokedex.put("피카츄", new Pokemon("라이츄"));

// 키들의 배열 .keySet()
pokedex.keySet();

// 반복문을 통한 value 찾기
for (String key : pokedex.keySet()) {
    System.out.println(pokedex.get(key));
}

HashMap sorting

- hashMap sorting은 키 리스트를 만들어서

해당 키 리스트를 hashMap의 값 혹은 키를 기준으로 정렬하는방법이다.

HashMap<String, Integer> genrePlays = new HashMap<>();
        for (int i = 0; i < plays.length; i++) {
            songs.add(new Song(genres[i], plays[i], i));
            // 해당장르가 추가가 안되었다면 plays[i]를 넣고 추가가 이미 되어있다면 plays[i]를 더한 것을 저장한다.
            genrePlays.put(genres[i], genrePlays.getOrDefault(genres[i], plays[i]) + plays[i]);
        }
        // HashMap을 value값 기준으로 정렬하기 위한 KeySetList
        ArrayList<String> keySetList = new ArrayList<String>(genrePlays.keySet());
        Collections.sort(keySetList, (o1, o2) -> genrePlays.get(o2).compareTo(genrePlays.get(o1)));

- 위코드를 보면

HashMap을 선언하고 keyList를 Collections.sort로 정렬한다. 정렬 기준을 hashMap의 값으로 잡는데,

기준을 key로 잡으면 key로 정렬된다.

 

* 추가로 HashMap은 키값의 중복이 허용이 안되는 만큼 put()메소드에서 키값이 이미 있다면 새로 들어오는 value 값이

덮어 쓰여지는데, 이를 getOrDefalut(키,  값) 함수로 가능하다, 키값이 없다면 값을 넣고 이미 키값이 있다면 기존값을 그대로 넣는다.

 

* 또 중복된 키의 값이 덮어쓰여질때 들어온 키값의 순서가 바뀐다.