사용자 도구

사이트 도구


wiki:java:java-lecture:2week

차이

문서의 선택한 두 판 사이의 차이를 보여줍니다.

차이 보기로 링크

양쪽 이전 판 이전 판
다음 판
이전 판
wiki:java:java-lecture:2week [2021/01/18 08:35]
iyyeo [타입 추론, var]
wiki:java:java-lecture:2week [2023/01/13 18:44] (현재)
줄 288: 줄 288:
  
 ==== 타입추론과 Generic Methods ==== ==== 타입추론과 Generic Methods ====
-타입추론덕분에 generic 메소드를 사용할 때 보통의 메소드처럼 특정 타입을 명시하지 않은 채로 호출할 수 있다.  +  * 타입추론덕분에 generic 메소드를 사용할 때 보통의 메소드처럼 특정 타입을 명시하지 않은 채로 호출할 수 있다. \\ 
-public class BoxDemo { + 
- public static <U> void addBox(U u, java.util.List<Box<U>> boxes) { +  public class BoxDemo { 
- Box<U> box = new Box<>(); +   public static <U> void addBox(U u, java.util.List<Box<U>> boxes) { 
- box.set(u); +   Box<U> box = new Box<>(); 
- boxes.add(box); +   box.set(u); 
- +   boxes.add(box); 
-+   
-public static <U> void outputBoxes(java.util.List<Box<U>> boxes) { +  
-    int counter = 0; +  public static <U> void outputBoxes(java.util.List<Box<U>> boxes) { 
-    for (Box<U> box: boxes) { +      int counter = 0; 
-      U boxContents = box.get(); +      for (Box<U> box: boxes) { 
-      System.out.println("Box #" + counter + " contains [" + +        U boxContents = box.get(); 
-             boxContents.toString() + "]"); +        System.out.println("Box #" + counter + " contains [" + 
-      counter++;+               boxContents.toString() + "]"); 
 +        counter++
 +      } 
 +    } 
 +   
 +    public static void main(String[] args) { 
 +      java.util.ArrayList<Box<Integer>> listOfIntegerBoxes = 
 +        new java.util.ArrayList<>(); 
 +      BoxDemo.<Integer>addBox(Integer.valueOf(10), listOfIntegerBoxes); //---(1) 
 +      BoxDemo.addBox(Integer.valueOf(20), listOfIntegerBoxes);//---(2) 
 +      BoxDemo.addBox(Integer.valueOf(30), listOfIntegerBoxes); 
 +      BoxDemo.outputBoxes(listOfIntegerBoxes);
     }     }
   }   }
  
 +\\
 +''(1)'' : addBox라는 generic 메소드를 호출할 때 <Integer> type witness와 함께 type parameter를 명시하여 사용할 수 있다.\\
 +''(2)'' :  Java 컴파일러가 메소드의 인자로부터 자동으로 Integer type임을 추론해주기 때문에 type witness를 생략할 수도 있다. \\
 +\\
 +==== 타입추론과 Generic 클래스의 인스턴스 ====
 +  * Java 컴파일러가 컨텍스트로부터 타입추론이 가능하다면 Generic 클래스의 생성자를 호출하기 위해 필요한 type arguments를 비어있는 type witness(<>, the diamond)로 대체할 수 있다. 
 +
 +  List<String> myList1 = new ArrayList<String>();
 +  List<String> myList2 = new ArrayList<>();
 +
 +\\
 +==== 타입추론과 Generic 생성자 ====
 +  * 클래스가 Generic/non-generic 인지 그 여부와 관계없이 생성자는 generic일 수 있다. 
 +
 +  class MyClass<X> {
 +    <T> MyClass(T t) {
 +      // ...
 +    }
 +  }
 +  
   public static void main(String[] args) {   public static void main(String[] args) {
-    java.util.ArrayList<Box<Integer>> listOfIntegerBoxes = +   MyClass<Integer> myInstance = new MyClass<Integer>("");
-      new java.util.ArrayList<>(); +
-    BoxDemo.<Integer>addBox(Integer.valueOf(10), listOfIntegerBoxes); //---(1) +
-    BoxDemo.addBox(Integer.valueOf(20), listOfIntegerBoxes);//---(2) +
-    BoxDemo.addBox(Integer.valueOf(30), listOfIntegerBoxes); +
-    BoxDemo.outputBoxes(listOfIntegerBoxes);+
   }   }
-} + 
-Java +  * MyClass의 type 매개변수 X에는 Integer가 들어가지만 생성자의 type 매개변수 T에는 String이 들어간다. \\ 
-(1): addBox라는 generic 메소드를 호출할 때 <Integertype witness와 함께 type parameter를 명시하여 사용할 수 있습니다. +\\ 
-(2):  Java 컴파일러가 메소드의 인자로부터 자동으로 Integer type임을 추론해주기 때문에 type witness를 생략할 수도 있습니다.  + 
-타입추론과 Generic 클래스의 인스턴스 +''Java SE 7''이전에는 컴파일러에서 실제 type argument를 작성해 타입 추론을 할 수 있었지만,\\ 
-Java 컴파일러가 컨텍트로부터 타입추론이 가능하다면 Generic 클래스의 생성자를 호출하기 위해 필요한 type arguments를 비어있는 type witness(<>, the diamond)로 체할 수 있다.  +''Java SE 7''이후로 컴파일러는 the diamond(''<>'')를 사용하는 경우 다음과 같이 ''generic'' 클래의 실제 ''type argument''까지 추론이 가능하다
-List<StringmyList1 = new ArrayList<String>(); + 
-List<String> myList2 new ArrayList<>(); +  MyClass<Integer> myInstance = new MyClass<>(""); 
-Java + 
-타입추론과 Generic 생성자 +\\ 
-클래스가 Generic/non-generic 인지 그 여부와 관계없이 생성자는 generic일 수 있다.  +==== Target Types ==== 
-class MyClass<X{ +  * Java 컴파일러는 generic method invocation의 type argument를 추론하기 위해 target typing의 이점을 이용다.  
-  <TMyClass(T t) { +  * 표현식의 target type이란 표현식이 나타낸 위치에 의존하여(컨텍스트 의존Java 컴파일러가 기하는 데이터 타입이다.\\ 
-    // ...+ 
 +  static <T> List<TemptyList() { return new ArrayList<>(); } 
 +  List<String> listOne Collections.emptyList(); 
 + 
 +  * 위 코드는 Collection API의 emptyList 함수를 이용해 List<String> 객체를 반환한다.  
 +  * 이런 데이터 타입을 Target Type라 하데, emptyList 함수가 List<T> 타입을 리턴하기에 컴파러에서 type argument T가 반드시 String일 것이라고 추론한다.  
 +  * 물론, type witness를 사용해 명시적 선언을 해줄 도 지만 위 코드에서는 불필요하다.\\ 
 +\\ 
 +  List<StringlistOne = Collections.<String>emptyList(); //불필요한 witness  
 + 
 + 
 +  * 하지만, Type Witness가 필요한 경우도 있다. 
 +\\ 
 + 
 +  void processStringList(List<StringstringList) { 
 +     //process stringList 
 +  } 
 +  public static void main(String[] args) { 
 +   processStringList(Colections.emptyList());
   }   }
-} 
  
-public static void main(String[] args) { +  * 위 코드에서 메소드 호출은 정상적으로 동작할까?  
- MyClass<Integer> myInstance = new MyClass<Integer>(""); +  Java SE 7 컴파일러에서는 컴파일 되지 않고 에러가 발생하며 아래와 같은 에러 메세지가 출력된다.
-+
-Java +
-⇒ MyClass의 type 매개변수 X에는 Integer가 들어가지만 생성자의 type 매개변수 T에는 String이 들어간다.  +
-Java SE 7 이전에는 컴파일러에서 실제 type argument를 작성해 타입 추론을 할 수 있었지만, Java SE 7이후로 컴파일러는 the diamond(<>)를 사용하는 경우 다음과 같이 generic 클래스의 실제 type argument까지 추론이 가능하다. +
-MyClass<Integer> myInstance = new MyClass<>(""); +
-Java +
-Target Types +
-Java 컴파일러는 generic method invocation의 type argument를 추론하기 위해 target typing의 이점을 이용한다. 표현식의 target type이란 표현식이 나타낸 위치에 의존하여(컨텍스트 의존) Java 컴파일러가 기대하는 데이터 타입이다  +
-static <T> List<T> emptyList() { return new ArrayList<>();+
-List<String> listOne = Collections.emptyList(); +
-Java +
-위 코드는 Collection API의 emptyList 함수를 이용해 List<String> 객체를 반환한다. 이런 데이터 타입을 Target Type이라 하는데, emptyList 함수가 List<T> 타입을 리턴하기에 컴파일러에서 type argument T가 반드시 String일 것이라고 추론한다.  +
-물론, type witness를 사용해 명시적 선언을 해줄 수도 있지만 위 코드에서는 불필요하다. +
-List<String> listOne = Collections.<String>emptyList(); //불필요한 witness  +
-Java +
-하지만, Type Witness가 필요한 경우도 있다. +
-void processStringList(List<String> stringList) { +
- //process stringList +
-+
-public static void main(String[] args) { +
- processStringList(Colections.emptyList()); +
-+
-Java +
-⇒ 위 코드에서 메소드 호출은 정상적으로 동작할까?  +
-Java SE 7 컴파일러에서는 컴파일 되지 않고 에러가 발생하며 아래와 같은 에러 메세지가 출력된다. +
-List<Object> cannot be converted to List<String>  +
-이런 에러가 발생하는 이유는 컴파일러는 type argument T를 위한 value를 필요한데, 아무것도 주어지지 않았기에 Object를 value로 삼게된다. 그 결과 Collections.emptyList()는 List<Object> 객체를 리턴하며 이는 processStringList에서 호환하지않는 인수타입이기에 에러가 발생한다.  +
-그렇기에 Java SE 7에서는 type witness를 명시해줘야 한다. +
-processStringList(Colections.<String>emptyList()); +
-Java +
-하지만, Java SE 8 부터는 위와 같은 경우에도 type witness를 명시해주지 않아도 Target type을 결정할 때 메소드의 argument도 살피도록 확장되었기 때문에 에러가 발생하지 않는다.  +
-그렇기 때문에 Java SE 8이상에서는 위의 type witness가 없는 메소드 호출도 정상적으로 동작할 것이다. +
-var +
-Java 10부터 추가된 특징중 하나인 Local Variable Type Inference은 로컬 변수 선언을 var를 이용하여 기존의 엄격한 타입 선언방식에서 컴파일러에게 타입추론 책임을 위임할 수 있게 되었다. +
-var list = new ArrayList<String>(); //infers ArrayList<String> +
-var stream = list.stream();//infers Stream<String> +
-Java +
-Local Variable Type Inference 사용 조건 +
-• +
-초기화된 로컬 변수 선언시 +
-• +
-반복문에서 지역변수 선언 시(enhanced for loop포함) +
-var 활용 +
-1. +
-지역변수 선언 +
-var numbers = Arrays.asList(1, 2, 3, 4, 5);+
  
-for (var i = 0; i numbers.size(); i++) { +  List<Object> cannot be converted to List<String> 
-    System.out.println("numbers = " + numbers.get(i)); +
-+
-Java +
-2. +
-forEach +
-var numbers = Arrays.asList(1, 2, 3, 4, 5);+
  
-for (var number : numbers) { +  * 이런 에러가 발생하는 이유는 컴파일러는 type argument T를 위한 value를 필요한데, 아무것도 주어지지 않았기에 Object를 value로 삼게된다.  
-    System.out.println(number); +  * 그 결과 Collections.emptyList()는 List<Object> 객체를 리턴하며 이는 processStringList에서 호환하지않는 인수타입이기에 에러가 발생한다.  
-+  * 그렇기에 Java SE 7에서는 type witness를 명시해줘야 한다. 
-Java + 
-⇒ 기존에는 Object타입으로 받아서 형변환을 하거나 IDE가 아닌 개발자가 직접 타입추론해 명시적 타입선언을 해줬는데 var를 사용하여 훨씬 편하게 타입선언이 가능해진다. +  processStringList(Colections.<String>emptyList()); 
-3. + 
-Lambda (Java 11) +  * 하지만, Java SE 8 부터는 위와 같은 경우에도 type witness를 명시해주지 않아도 Target type을 결정할 때 메소드의 argument도 살피도록 확장되었기 때문에 에러가 발생하지 않는다.   
-IntBinaryOperator plus10 = (@NonNull var one, @NonNull var two) -> one + two + 10; +  * 그렇기 때문에 Java SE 8이상에서는 위의 type witness가 없는 메소드 호출도 정상적으로 동작할 것이다.\\ 
-Java +\\ 
-⇒ Java 11부터는 람다 인자에도 var사용이 가능해졌는데, 이를 통해 파라미터 어노테이션 사용까지 가능해졌다.  +==== var ==== 
-참고: 비어있는 type witness를 사용하면 Object로 추론한다.+  * Java 10부터 추가된 특징중 하나인 Local Variable Type Inference은 로컬 변수 선언을 var를 이용하여 기존의 엄격한 타입 선언방식에서 컴파일러에게 타입추론 책임을 위임할 수 있게 되었다. 
 + 
 +  var list = new ArrayList<String>(); //infers ArrayList<String> 
 +  var stream = list.stream();//infers Stream<String> 
 + 
 +\\ 
 + 
 +==== Local Variable Type Inference 사용 조건 ==== 
 +  * 초기화된 로컬 변수 선언시 
 +  * 반복문에서 지역변수 선언 시(enhanced for loop포함) 
 + 
 +==== var 활용 ==== 
 + 
 +**1. 지역변수 선언** 
 +   
 +  var numbers = Arrays.asList(1, 2, 3, 4, 5); 
 +   
 +  for (var i = 0; i < numbers.size(); i++) { 
 +      System.out.println("numbers = " + numbers.get(i)); 
 +  } 
 +\\ 
 + 
 +**2. forEach** 
 +   
 +  var numbers = Arrays.asList(1, 2, 3, 4, 5); 
 +   
 +  for (var number : numbers) { 
 +      System.out.println(number); 
 +  
 + 
 + 
 +  * 기존에는 Object타입으로 받아서 형변환을 하거나 IDE가 아닌 개발자가 직접 타입추론해 명시적 타입선언을 해줬는데 var를 사용하여 훨씬 편하게 타입선언이 가능해진다.\\ 
 +\\ 
 +**3. Lambda (Java 11)** 
 + 
 +  IntBinaryOperator plus10 = (@NonNull var one, @NonNull var two) -> one + two + 10; 
 + 
 +  Java 11부터는 람다 인자에도 var사용이 가능해졌는데, 이를 통해 파라미터 어노테이션 사용까지 가능해졌다.  
 +  * ''참고'': 비어있는 type witness를 사용하면 Object로 추론한다.
 ===== Ref ===== ===== Ref =====
-https://catsbi.oopy.io/6541026f-1e19-4117-8fef-aea145e4fc1b +[[https://github.com/whiteship/live-study/issues/2|https://github.com/whiteship/live-study/issues/2]] \\ 
-https://github.com/whiteship/live-study/issues/2+ 
 +[[https://blog.naver.com/hsm622/222144931396|https://blog.naver.com/hsm622/222144931396]] \\ 
 +[[https://www.notion.so/damho1104/2-38b5d67c7f5a48238529bb8f1617ea0d|https://www.notion.so/damho1104/2-38b5d67c7f5a48238529bb8f1617ea0d]] \\ 
 +[[https://velog.io/@jaden_94/2%EC%A3%BC%EC%B0%A8-%ED%95%AD%ED%95%B4%EC%9D%BC%EC%A7%80|https://velog.io/@jaden_94/2%EC%A3%BC%EC%B0%A8-%ED%95%AD%ED%95%B4%EC%9D%BC%EC%A7%80]] \\ 
 +[[https://github.com/kksb0831/Practice_project/blob/master/Java_Study_02.md|https://github.com/kksb0831/Practice_project/blob/master/Java_Study_02.md]] \\ 
 +[[https://catsbi.oopy.io/6541026f-1e19-4117-8fef-aea145e4fc1b|https://catsbi.oopy.io/6541026f-1e19-4117-8fef-aea145e4fc1b]] \\ 
 +[[https://www.notion.so/2-00ffb2aeb41d450aa446675b8a9e91d5|https://www.notion.so/2-00ffb2aeb41d450aa446675b8a9e91d5]] \\ 
 +[[https://b-programmer.tistory.com/225|https://b-programmer.tistory.com/225]] \\ 
 +[[https://github.com/yeo311/java-study-with-whiteship/tree/main/week2|https://github.com/yeo311/java-study-with-whiteship/tree/main/week2]] \\ 
 +[[https://blog.naver.com/swoh1227/222149491648|https://blog.naver.com/swoh1227/222149491648]] \\ 
 +[[https://catch-me-java.tistory.com/14|https://catch-me-java.tistory.com/14]] \\ 
 +[[https://catch-me-java.tistory.com/15|https://catch-me-java.tistory.com/15]] \\ 
 +[[https://catch-me-java.tistory.com/16|https://catch-me-java.tistory.com/16]] \\ 
 +[[https://catch-me-java.tistory.com/17|https://catch-me-java.tistory.com/17]] \\ 
 +[[https://catch-me-java.tistory.com/18|https://catch-me-java.tistory.com/18]] \\ 
 +[[https://catch-me-java.tistory.com/19|https://catch-me-java.tistory.com/19]] \\ 
 +[[https://catch-me-java.tistory.com/20|https://catch-me-java.tistory.com/20]] \\ 
 +[[https://docs.google.com/presentation/d/1Ni0FMbVBSTxiOWHvp928quGT8sTjTG_ZuAWxaCFGT1E/edit?usp=sharing|https://docs.google.com/presentation/d/1Ni0FMbVBSTxiOWHvp928quGT8sTjTG_ZuAWxaCFGT1E/edit?usp=sharing]] \\ 
 +[[https://github.com/league3236/startJava/blob/master/live_study/week2.md|https://github.com/league3236/startJava/blob/master/live_study/week2.md]] \\ 
 +[[https://github.com/Rebwon/TIL/blob/master/live-study/second.md|https://github.com/Rebwon/TIL/blob/master/live-study/second.md]] \\ 
 +[[https://github.com/yeGenieee/java-live-study/blob/main/%5B2%5DJava%20Live%20Study.md|https://github.com/yeGenieee/java-live-study/blob/main/%5B2%5DJava%20Live%20Study.md]] \\ 
 +[[https://scshim.tistory.com/169|https://scshim.tistory.com/169]] \\ 
 +[[https://www.notion.so/2-4bc4a76a553d46b78d7ad1af6fa7df2b|https://www.notion.so/2-4bc4a76a553d46b78d7ad1af6fa7df2b]] \\ 
 + 
 + 
 + 
 + 
 + 
 + 
 + 
  
 {{tag>와프}} {{tag>와프}}
/volume1/web/dokuwiki/data/attic/wiki/java/java-lecture/2week.1610926526.txt.gz · 마지막으로 수정됨: 2022/03/10 19:52 (바깥 편집)