본문 바로가기

개발기술/Java

Java 코딩구현 기초 - 데이터타입

변수

데이터를 저장하는 메모리 공간에 붙여준 이름

  • 변수를 만들기 위해서는 1. 변수선언(데이터형 변수이름; int a ) 2. 변수에 값 초기화 (변수명 = 데이터값, a=10)를 할 수 있으며 동시에 혹은 따로 모두 가능하다.
  • **참고**: 지금 학습하는 변수는 지역 변수(Local Variable)라고 하는데, 지역 변수는 개발자가 직접 초기화를 해주어 야 한다. 나중에 배울 클래스 변수와 인스턴스 변수는 자바가 자동으로 초기화를 진행해준다.
  • 기본형(Primitive Type) vs 참조형 (Reference Type)
    • 자바의 변수 데이터 타입을 가장 크게 보면 기본형과 참조형으로 분류할 수 있다. 사용하는 값을 직접 넣을 수 있는 기본 형, 그리고 메모리의 참조값을 넣을 수 있는 참조형으로 분류할 수 있다.
    • 기본형(Primitive Type): `int` , `long` , `double` , `boolean` 처럼 변수에 사용할 값을 직접 넣을 수 있는 데이터 타입
    • 참조형(ReferenceType):`int[] students` 와 같이 데이터에 접근하기위한참조(주소)를저장하는 데이터 타입이다.
      • 기본형은 선언과 동시에 크기가 정해진다. 반면 배열은 런타임에 동적으로 사이즈가 결정되어 메모리 사용이 효율적이다.
      • 배열의 선언 : 배열 변수를 선언한다는 것은 배열 주소의 참조값을 보관할 수 있는 변수를 선언하는 것이다.`new` 는 class의 instance를 새로 생성한다는 뜻이고, 생성한 배열에 접근하는 방법인 참조값은 students라는 변수에 보관되는 것이다.
  • 정수형
    • `byte` : -128 ~ 127 (1byte, 28). 용량이 작아 거의 사용하지 않는다.
    • `short` : -32,768 ~ 32,767 (2byte, 216). 용량이 작아 거의 사용하지 않는다.
    • `int` : -2,147,483,648 ~ 2,147,483,647 (약 20억) (4byte, 232) `int` 범위인 약 20억 을 넘어가면 `L` 을 붙여서 정수 리터럴을 `long` 으로 변경해야 한다.
      • int numBase2 = 0b1100; 2진수표기법
      • int numBase8 = 014; 8진수 표기법
      • int numBase16 = 0xC; 16진수 표기법
    • `long` : -9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807 (8byte, 264)
  • 실수형
    • `float` : 대략 -3.4E38 ~ 3.4E38, 7자리 정밀도 (4byte, 232). 소수점의 정밀도가 낮아 거의 사용하지 않는다.
    • `double` : 대략 -1.7E308 ~ 1.7E308, 15자리 정밀도 (8byte, 264)
  • 기타형
    • boolean` : `true` , `false` (1byte)
    • char` : 문자 하나를 표현하며 ''로 input 한다. (2byte), 거의 사용하지 않는다.
      • char 문자타입을 int가 입려되어야할 자리에 사용하면 자동형변환이된다. 이때, 해당하는 유니코드가 출력되며, 반대로 int의 경우 char로 사용하고 싶으면 명시적 형변환이 필요하다. A에 대응하는 아스키 코드는 65이다. (int 0~9 :: ASC 48~57, Char A~Z :: 65~90, Char a~z 97~122
      • method : Character.isDigit(char ch) / isLetter(char ch) / isWhitespace(char ch) / isAlphabet(char ch) / isDigit / Character.isLetterOrDigit()
    • var : Java10부터 사용가능함. 저장되는 데이터의 변수타입에 맞추어 변수타입을 변환해준다. 로컬변수로만 사용가능.

 

Object

모든 객체의 최상위 부모객체로 객체의 속성을 정의한다. 모든 클래스의 최고 조상, 오직 11개 메서드만 가지고 있음

 

Method

  • object.clone() : 객체 자신의 복사본을 생성하여 새로운 객체를 만든다. 단, shallow cloning은 object field가 참조값일 경우 그 참조값도 복사하여 동일한 객체를 참조할 수도있다. 단, deep cloning은 field가 객체를 가르킬때 가르키는 객체도 생성한다.
  • instance.equals(object) : 객체 자신과 주어진 객체의 주소를 비교한다. 같으면 true, 다르면 false를 반환. 단, 대부분의 하위 클래스는 인스턴스의 변수 값 (string, literal은 같은 값이면 동일한 주소를 갖도록 java 최적화 되어있음)
  • instance.toString() : 객체의 자신의 정보를 문자열로 변환
  • wait() - Thread관련 메소드, 향후 추가
  • notify() - Thread관련 메소드, 향후 추가
  • hashcode() : to return an integer representation of an object's memory address of value which is then used by hashing algorithms.

 

String Object : 문자열을 표현하는 클래스. 

 

String의 특성

  • Immutability : String class are immutable to save memory and performance in scenarios where a fixed string is used frequently. Any operation that seems to modify a string actually creates a new string.
  • 스트링의 경우 메모리 저장에는 유리하지만, 수정변환에는 비효율적이기에 append, insert, or delete characters or substrings 을 빈번하게 할때는 StringBuffer을 사용함.

String 생성방법

 

  • new String(chararray)
  • String.valueOf(chararray)

 

String Method

  • String.toCharArray() : char단위로 조회 및 조작이 필요할때는 char[]으로 toCharArray()로 변환하여 사용하고 조작이 완료된 이후에는 String.valueOf(array)로 재변환할 수 있음,
  • length() :Returns the length of the string (the number of characters).
  • contains(CharSequence s) : Returns true if and only if this string contains the specified sequence of char values.
  • startsWith(String prefix), endsWith(String suffix) : Tests if this string starts with the specified prefix.
  • indexOf(char/String, int fromIndex): Returns the first index within this string of the first occurrence of the specified character, starting the search at the specified index. If not found return -1.
    • 두번째 occurence of 문자 : str.indexOf("!",str.indexOf("!")+1)
    • LastIndexOf(char/String, int fromIndex): Searches for the last occurrence of the specified character, starting the search at the specified index and moving backward. return first index of first character
  • instance.replace(char oldString, char newString): Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
  • instance.matches(String regex) : used to check and return true/false if the entire string matches a given regular expression.
  • instance.replaceall(String regex, newChar) : 
  •  
  • Stringinstance.toCharArray method : used to convert a String into a new character array (char[])
  • substring(int startindex, int endindex(생략)): Returns a new string that is a substring of this string by index from start to end -1 index. endindex mean upperbound(stopping point )for indexing
  • toLowerCase() ,toUpperCase() : converts all the characters in a given string to upper,lowerrcase.
  • charAt(i) : Accessing the first character 'H'
  • trim() : Returns a copy of the string, with leading and trailing whitespace omitted.
  • split(String 구분자) : to split a string into an array of substrings based on a given delimiter
    • string tokenizer을 대신해서 사용한다
  • String.join(delimiter, items) : concatenate items (element) with delimiters between items.
  • String.format(String format, Object... args) : method returns a formatted string using the specified format string and arguments. printf에도 동일한 문법으로 적용가능함.

 

String Formatter

 

format specifier : %[flags:keyword][width:number][.precision:number]conversion:character

  • flags - Optional. Provides additional formatting options like alignment, padding, etc
    • (minus): Left-align the output within the specified width.
  • + (plus): Ensures the output shows a plus or minus sign for numeric values.
  • 0 (zero): Enables zero-padding. When width is specified, the output is padded with zeros instead of spaces.
  • (space): Adds a leading space before positive numbers (useful in signed numeric outputs to align positive and negative values).
  • , (comma): Adds grouping separators (typically used for thousands).
  • width : Optional. 특정숫자를 입력하면 해당 숫자만큼 space로 칸을 채워줌
    • 예시 ; %9s : string을 출력하고 남는 공간은 space로 채워서 9칸을 출력
  • .precision - Optional. Specifies the number of digits of precision when outputting floating-point values or the maximum number of characters for strings.
  • conversion : %s: string(입력값이 객체이면 tostring으로 변환해서 출력해줌), %d: a decimal integer, %f: a floating-point number, %t: date and time conversions (e.g., %tY for the year), %% : to print '%'.

 

Regular Expression(Regex)

 

  regular expression(regex) can match complex patterns of characters with various behaviors. this is cross language and platform expression.

  • . (dot): 어떤 문자든 문자를 1개 매칭시켜준다; Matches any single character, except newline character.
  • ^: 1. 소스의 여러 매치대상중 앞에 있는 문자대상을 지목할때 사용. 2. [^] 괄호안에 사용되면 부정의 의미로 괄호안의 문자 외의 것을 선택
  • $ : 소스의 여러 매치대상중 뒤에 있는 문자대상을 지목할때 사용. Anchors the regex to the end of a line.
  • \ :  $와 같은 특수기능문자를 기능을 없애고 literal로 취급하고 싶을때  Used to escape special characters
    • \\ : In Java, because the backslash (\) is also an escape character in strings, we need to escape the backslash itself by writing it as \\ . o \\s in a Java string represents \s in the regex, which matches any whitespace character.
  • []:  괄호안에 복수의 문자 중 하나의 문자 중에서 하나의 문자로서 매치를 찾음.A character class that matches any one of the characters inside the brackets.
  • s : white space
  • w : word라는 표현으로 알파벳,숫자,_를 포괄하는 문자를 지칭
  • W : not word로 w를 제외한 모든 것을 지칭
    • - : 괄호안에 여러가지 문자가 들어가야한다면 범위로 지정이 가능함 [A-Z]
  • 수량자 : 문자의 수량을 지정한다
    • * : a*b일시, * 앞의 문자(a)가 0~여러개 있는 것을 매치시킨다.
      • (=={0,}), *? 두가지 수량자의 조합은 0을 의미한다.
    • + : a+b일시, + 앞의 문자(a)가 1~여러개 있는 것을 매치시킨다.
      • (=={1.}) *+ 두가지 수량자의 조합은 1을 의미한다.
    • ? : a?b일시, ?앞의 문자(a)가 0~1개 있는 것을 매치시킨다.
      • (=={0,1}) *+ 두가지 수량자의 조합은 0을 의미한다.
    • {} : 괄호안에 숫자만큼의 앞의 문자를 지정한다
      • {a,b} {a,}{.b} a이상 b이하의 숫자만큼의 문자를 지정한다.
  • |: 복수문자를 or 관계로 엮어줌. (문자1|문자2|문자3) Logical OR operator.
  • (): Groups parts of the regex together and captures content. 

 

StringBuilder

 

  문자열을 자주 추가하거나 변경할때 사용하는 자료형. DS관점에서 Dynamic Array와 유사하며 기능적으로 StringBuilder와 거의 동일하다. 쓰레드 안정성에서 Single Thread에서는 StringBuilder, Multi Thread에서는 StringBuffer을 사용한다. Builder는 Ram에서 메모리를 충분히 할당받으나 buffer은 ram에서 8000char 가량밖에 할당되지 않고 꽉 찰시 flush를 통해 file로 저장한다.  stringbuffer은 크키는 한정되지 않으나 synchronization을 위해 lock이 구현되어 있어 비교적 비효율적이다.

  • StringBuilder variable = new StringBuilder("text")
  • method
    • append(str,char): Appends the specified string to this character sequence.
      • string에서 a+b로도 concatnation이 가능하지만 string buffer은 dynamic하게 크기가 변하기 때문에 static한 string에 비해서 메모리 비효율적이다.
    • insert(index, String str): Inserts the specified string into this character sequence.
    • delete(strindex, endindex) : Removes the characters substring that begins at the specified start and to at index end - 1
    • reverse() : Reverses the characters within the StringBuffer.
    • setLength() - Sets or adjusts the length of the character sequence. If the new length is shorter, the sequence is truncated; if longer, it is padded with null characters ('\u0000').
    • toString() : Converts Stringbuilder to String
    • String과 공용메서드 : charat(index), substringsubstring(int beginIndex, int endIndex), 
    •  
  • Method
    • compareTo(Wrapper obj): Compare two objects of the wrapper class.
    • equals(Object obj): Check if the object is equal to another object, considering type and value.
      • '=='와 약간의 차이가 있는데, equals는 값을 비교하며 ==는 객체가 동일한지 비교하는 것이다. literal은 기존에 있는 데이터와 동일한 데이터가 있을 경우 같은 객체로 저장하기에 equals와 == 모두 true가 나올 수 있
  • Assignment
    • int a ,b = 4,3 (x) int a = 4, b = 3;(o)
    • n Java, when you perform an assignment, the expression itself evaluates to the assigned value.
      • 그러므로 다음과 같은 식이 사용가능한다. assignment인 동시에 return 값을 생성하기 때문이다. while ((input = scanner.nextInt()) != -1

 

데이터 간 형변환

자동형변환:

  • 작은 범위의 데이터 타입에서 큰 범위로의 대입은 자바에서 자동으로 허용됩니다. 예를 들어, int를 double로 변환할 수 있지만, 반대로 double을 int로는 자동으로 변환할 수 없습니다.

 

명시적형변환:

  • 큰 범위에서 작은 범위로의 대입은 명시적인 형변환이 필요합니다. 예를 들어, intValue = (int) doubleValue;와 같이 형변환을 지정해야 합니다.
  • 만약 작은 범위가 표현할 수 있는 숫자의 범위를 넘어서면 오버플로우가 발생하여 최소값에서 다시 최대값으로 돌아가는 문제가 생길 수 있습니다.
  • 예를 들어, 3/2와 같이 int형끼리 나눗셈을 하면 소수가 버려져서 결과가 1이 됩니다. 소수까지 계산하고 싶다면, (double) 3/2처럼 명시적 형변환을 사용해야 합니다.

형변환 가능 범위:

  • 형변환은 primitive 타입 간, 그리고 상속 관계에 있는 객체 간에서 가능합니다.

 

Wrapper 클래스:

  • 원시 데이터 타입을 객체로 감싸는 클래스입니다. 예를 들어, Integer i = new Integer(5);와 같이 int를 Integer 객체로 만들 수 있습니다.
  • 오토박싱(AutoBoxing): 자바는 자동으로 원시 타입을 Wrapper 클래스로 변환해줍니다. 예를 들어, Integer i = 5;로 간단하게 표현할 수 있습니다.

 

형변환 메서드:

  • Literal → Wrapper 객체: Integer.valueOf(Primitive data/string)와 같이, 원시 데이터를 Wrapper 객체로 변환할 수 있습니다.
  • 문자열 → 원시 데이터: Integer.parseInt("123")와 같은 메서드를 사용하여 문자열을 원시 데이터 타입으로 변환할 수 있습니다. parseInt의 경우 radix 옵션을 통해 2진수, 16진수 문자열도 10진수로 변환 가능합니다.  (Long.parseLong(), Double.parseDouble(),string.charAt(),Boolean.parseBoolean() ...)
  • Wrapper 객체 → 원시 데이터: integerInstance.intValue()와 같이 Wrapper 객체에서 원시 값을 꺼낼 수 있습니다.

 

배열과 컬렉션 간의 변환:

  • 원시 타입 배열과 Wrapper 객체를 사용하는 컬렉션 간에는 직접적인 형변환이 불가능하며, 하나씩 순회하면서 변환해야 합니다.
    • for문 변환: 반복문을 사용하여 원시 타입과 Wrapper 객체 간 1:1로 변환하는 방식입니다.
    • Stream 변환: 예를 들어, 배열을 리스트로 변환할 때는 Arrays.stream(numbers).boxed().collect(Collectors.toList())를 사용할 수 있습니
  •  

 

배열 Array

많은 수의 데이터를 담을 수 있는 자료형, 메모리 사이즈와 type safety가 고정되어있음

  • 배열의 생성
    • 1. int[] students; 배열 변수 선언, students = new int[5] {e1,e2,e3,e4,e5}; 배열의 길이를 구체화하여 배열생성
    • 2. int[] students = new int[] {e1,e2,e3,e4,e5}; 배열선언과 배열 요소 정의 동시실행
    • 3. int[] students = {e1,e2,e3,e4,e5}; 변수의 선언과 요소의 정의
    • 4. 배열의 변환 : arrayList.toArray(new type[0]) : arrayList instance를 변환하여 element크기의 array를 생성하고 각 element를 삽입한다. 단, wrapper class 에서 wrapper class array로만 변환가능함. primitve data는 별도의 type casting이 필요함.
    • 5. 배열 초기화 : 배열은 항상 default value로 초기화되어 생성됨
  • 2차원 배열의 선언
    • 1. `inx`xxt[][] arr = new int[2][3] // 배열 초기화 2. int[][] arr = { {1, 2, 3}, {4, 5, 6} } // 배열 요소 정의를 통한 초기화
  • 배열의 메소드 및 필드
    • 배열의 요소 조회 : element = array[index] (반면, ArrayList는 get메소드를 통해 조회함)
    • 배열의 요소 입력 : array[index] = element (반면, ArrayList는 add메소드를 통해 입력함)
    • 배열의 출력 : instancce.toString() - 주소값 출력, Arrays.toString(instance) - 내용물출력 (반면, ArrayList는 instance.toString()은 내용물을 출력함)
    • instance.length : 배열의 길이를 return한다. (반면, ArrayList는 ArrayList.length() 메소드를 사용함)
    • Arrays.sort(arry,fromindex,toindex) : Optionally, from Index and toIndex for partial array sorting.
      • 단, int[] arrays method는 reverse sorting을 지원하지 않아, integer로 변환을 거쳐야한다. 그러므로, stream을 통한 sorting이 더욱 보편적이다.
      • sorted = Arrays.stream(arr).sorted().toArray(Integer[]::new)
    • Arrays.asList(배열객체 or 배열요소1,2,3,4) : to convert an array into a fixed-size list
    • Arrays.copyOf(arry, newlength) : Returns a copy of the given array, truncated or padded with zeros if necessary to the newLength specified.
    • Array.binarysearch(arry, val) : Uses binary search to find the key in the sorted array. It returns the index of the key, or a negative number if the key is not found.
    • Arrays.fill(array, val) : Assigns the specified val to each element of the specified array a.
    • Arrays.stream(numbers).sum(); Arrays.stream(array) is used to create a stream and for various calcution such as max, min, avr, sum

 

 

컬렉션 상속관계 간략도식
컬렉션 상속관계 및 메소드

Java Collections Framework Hierarchy

  • java.lang.Object
    • java.util.Collection (interface)
      • java.util.List (interface)
        • ArrayList
        • LinkedList
        • Vector
          • Stack
      • java.util.Set (interface)
        • java.util.SortedSet (interface)
          • java.util.NavigableSet (interface)
            • TreeSet
        • HashSet
          • LinkedHashSet
      • java.util.Queue (interface)
        • java.util.Deque (interface)
          • ArrayDeque
          • LinkedList
        • PriorityQueue
        • java.util.concurrent.BlockingQueue (interface)
          • ArrayBlockingQueue
          • LinkedBlockingQueue
          • PriorityBlockingQueue
          • DelayQueue
          • SynchronousQueue
          • java.util.concurrent.TransferQueue (interface)
            • LinkedTransferQueue
        • java.util.concurrent.BlockingDeque (interface)
          • LinkedBlockingDeque
    • java.util.Map (interface)
      • java.util.SortedMap (interface)
        • java.util.NavigableMap (interface)
          • TreeMap
      • HashMap
        • LinkedHashMap
      • Hashtable
      • java.util.concurrent.ConcurrentMap** (interface)
        • ConcurrentHashMap
      • WeakHashMap
      • IdentityHashMap

 

컬렉션즈 프레임워크 (Colletion (List + Set + Queue) + Map) :

  사이즈가 고정된 배열과달리, 유동적으로 데이터를 관리할 수 있게 만들어 놓은 데이터구조 모음. 인터페이스 별로 데이터를 다루는 성격이 다르며 그 아래에 세부적 구현방법의 차이가 있음.

  • 컬렉션즈 프레임워크에서는 서로 상속관계로 이루어져있는데, 특정 클래스에만 해당되는 메소드를 사용하는 경우가 아니라면 공통의 인터페이스로 참조변수를 설정하여 유연성을 높이는 것을 추천한다
    • List stringList = new ArrayList<>(stringSet)
    • Collection shelter = new ArrayList<>();
  • 공통메서드
    • arrayList.toArray(new type[0]) : arrayList instance를 변환하여 element크기의 array를 생성하고 각 element를 삽입한다. 별도의 type casting은 불필요함.
    • toString() : make element of collections readable string.
    • add/
    • addall(collection) : is used to add all of the elements in a specified collection to the end of the list
    • remove(object o)
    • removeall(collection) : is used to remove all elements from the ArrayList that are also contained in the specified collection
    • contains(object) : used to check if the ArrayList contains data
    • containsall(collection) : used to check if the ArrayList contains all the elements in the specified collection
    • size : Returns the number of elements in this list
    • clear() : Removes all of the elements from this list. The list will be empty after this call returns
    • isEmpty()
    • iterator() : call Iterator interface and greate implemented instance from each collection differently for controlling how elements are accessed sequentially and is commonly used to cycle through collections in Java.
      • iterator.hasNext(): This method returns true if the iteration has more elements
      • iterator.next(): Returns the next element in the iteration. This method can throw a NoSuchElementException if no more elements exist

 

List Interface : 순서가 있는 데이터 집합, 데이터간 중복 허용

  • creation : 
    • 배열클래스를 사용하여 List를 생성 : Arrays.aslist(e1,e2...), Arrays.aslist(arrayinstance)
    • new ArrayList<>(existinglist), List.of(element)
    • 주의 : new ArrayList<> (intvalue)는 intvalue를 element로 설정하는 것이 아니라 intvalue만큼의 사이즈를 갖는 빈 arraylist를 생성한다. element를 설정하려 List.of(element) 형태로 초기화 입력해주어야한다.
  • Method
    • get(int index): Retrieves the element at the specified index in this list
    • add(E) : Adds the specified element E to the end of the list.
    • add(int index, E element): Inserts the specified element E at the specified position index in this list
    • remove(Object o / primitive data): Removes the first occurrence of the specified element from this list and return the value. 일반 숫자의 경우 index로 인식할 수 있기때문에 Integer.valueOf(2)로 표현
    • remove(int index): Removes the element at the specified position in this list.
    • indexOf(value) : To return the index of the first occurrence of the specified element in the list, or -1 if the list does not contain the element.
    • list.sort(list,Comparator.naturalOrder() / Comparator.reverseOrder()): The instance list itself is modified so that its elements are in the order imposed by the Comparator. ( Collections의 static method를 활용해서 Collections.sort(list,Comparator.naturalOrder)도 사용가능)
      • Comparator
      • C
    • list.set(index, element) : to replace an element in a list at a specified position.

 

 

ArrayList

  • creation : 
    • new ArrayList<>(size);
    • new ArrayList<>(existinglist); - new ArrayList<>(List.of("apple""banana""cherry")),
    • new ArrayList<> (Arrays.aslist(e1,e2...))
      • 기존의 Arrays를 ArrayList로 변환할 때 primitive type의 Array면 wrapperClass로 변환이 필수적임. 그렇지 않으면 int[]인 object type의 list로 인식됨.
      •  
    •  
  •  

 

Linked list : implements the List and Deque interfaces, providing a doubly linked list implementation of these interfaces; This structure allows for efficient insertion and removal of elements at both ends, as well as anywhere in the list.

  • Method
    • addFirst(val)
    • addLast(val)
    • removeFisrt()
    • removeLast()

ArrayDeque : a resizable, array-based implementation of the Deque (double-ended queue) interface in Java. Essentially, it acts as a general-purpose queue or stack that supports adding and removing elements from both ends.

 

  • Method
    • addFirst(E e): Adds the specified element to the front of the deque.
    • addLast(E e): Adds the specified element to the end of the deque.
    • removeFirst(): Removes and returns the first element (head) of the deque. Throws an exception if the deque is empty.
    • removeLast(): Removes and returns the last element (tail) of the deque. Throws an exception if the deque is empty.

 

 

 

Vector v = new Vector();

 

Set 인터페이스 : 순서가 없는 데이터의 집합, 데이터의 중복 허용 하지 않음

  • HashSet : Set interface that uses a hash table as its underlying data structure.
  • HashSet set1 = new HashSet();
    • add(val)
    • remove(val)
    • size()
    • contains()
  • TreeSet set2 = new TreeSet();
    • add(val)
    • remove(val)
    • first()
    • last()
    • lower(val) : val보다 더 작은 값을 return
    • higher(val) : val보다 더 큰 값을 return

 

 

Map 인터페이스 :

키와 값의 쌍으로 이루어진 데이터 집합,순서를 유지 하지 않음. Collections framework에 속하지만 Collection inteface를 상속하지 않고 map interface 독립적으로 존재함.

  • Map.Entry : key와 value를 한쌍으로 묶은 generics data type interface.  This set view is very useful for iterating over a map's contents with entrySet method
    • getKey()
    • getValue()
    • setValue()
  • method :
    • map.containsKey(Object key) / containsvalue(Object value) Returns true if this map contains a mapping
    • map.isempty()
    • map.put (key, value ) : Adds a key-value pair to the HashMap. If the map previously contained a mapping for the key, the old value is replaced.
    • map.get(Object key): Returns the value to which the specified key is mapped, or null
    • map.getOrDefault(Object key, V defaultValue) : retrieving a value from a map or returning a default value if the key is not found.
    • map.remove (object key) : Removes the mapping for a key from this map if it is present. Returns the value to which this map previously associated the key, or null if the map had no mappingx
    • HashMap의 순회 ;  for (Map.Entry<Character, Integer> entrymap : map.entrySet())
      • entry.entrySet() : key-value pair을 Map.entry라는 타입의 객체타입으로 만들어 set에 저장하여 반환한다.
        • entry.getkey()/ entry.getvalue() : key와 value값을 추출 할 수 있음
      • map.keySet() : 모든 ket값을 저장한 set을 반환한다.
      • map.values() : 모든 value값을 저장한 set을 반환한다.
  • HashMap :
    • Hashtable은 HashMap의 legacy버전으로 주로 HashMap을 사용한다.
    • 차이점 : 1. Hashtable에는 값으로 Null 사용불가 2. Hashtable은 스레드세이프하여 멀티스레드에서 우수, HashMap은 스레드세이프하지않아 싱글스레드에서 우수 (단, HashMap을 대체하여 스레드세이프한 SynchronizedHashMap, ConcurrentHashMap도 존재함)
    • 순서가 없으며 순서를 유지하려면 LinkedHashMap을 사용하자.
  • TreeMap = map2 = new TreeMap();
    • Treeset과 유사한 구조이며  범위구조와 정렬에 유리한 구조임. 단, 데이터추가와 삭제에는 더 시간이 걸림.
    • firstEntry() : 가장 처음 입력한 데이터 쌍
    • firstKey()
    • lastEntry()
    • lastKey()
    • lowerEntry(key)
    • higherEntry(key)
for (Map.Entry<Character, Integer> entrymap : map.entrySet())
  • 자료형 – 제네릭스 (Generics)
    • 자료형을 명시적으로 지정하여 안정성을 높여주고 데이터를 추출할때 형변환을 하는 과정을 줄여줌. 제네릭을 사용하지 않는다면 모든 데이터를 'object'라는 superclass로 upcasting변환된 후 저장됨. 
      • Generics에 wildcard ?을 사용하면 어떤 타입이든 다 받아줄 수 있다.
    • HashMap<String, String> map = new HashMap<String,String>();
    • implement Interface<T> : Interface of implementation need to specify the type parameter when implementing the interface
  • Collections 유틸리티 클래스 
    • Collections.sort(List, Comparator)  : 
    • Collections.binarySearch(List, Key, Comparator)  : perform a binary search
    • Collections.shuffle(list) : To randomize the order of elements in a list
    • Collections.reverse(List) :  reverse the order of elements in a list
    • Collections.max/min(collection)
    • Collections.copy(destList, srcList) : To copy all elements from one list into another