산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> java

Java Diamond Operator:Java 7+에서 제네릭 단순화

자바 다이아몬드 연산자

다이아몬드 연산자는 Generics에서 코드를 더 읽기 쉽게 만들기 위해 Java 7에 도입되었습니다. 제네릭은 인수의 한 유형입니다. generic을 사용하면 클래스 메서드에서 처리할 모든 종류의 객체를 전달할 수 있습니다. 예를 들어 Java 7 이전에 문자열 목록을 생성하는 경우 다음 구문을 사용하여 ArrayList 객체로 문자열 목록을 인스턴스화해야 합니다.

List<String> listOfStrings = new ArrayList<String>();

Java 7부터는 다이아몬드 연산자를 사용하여 위 구문을 다음과 같이 단순화할 수 있습니다. −

List<String> listOfStrings = new ArrayList<>();

그러나 익명 내부 클래스에서는 사용할 수 없습니다. 예를 들어, Java 9 이전 버전에서는 아래 구문의 다이아몬드 연산자에서 객체 유형을 생략할 수 없습니다.

Handler<Integer> intHandler = new Handler<Integer>(1) {
 @Override
 public void handle() {
 System.out.println(content);
 }
};

익명 클래스의 다이아몬드 연산자

Java 9에서는 다이아몬드 연산자를 익명 클래스와 함께 사용하여 코드를 단순화하고 가독성을 높일 수 있습니다.

Handler<Integer> intHandler = new Handler<>(1) {
 @Override
 public void handle() {
 System.out.println(content);
 }
};

Java 7, Java 8의 다이아몬드 연산자

아래 예에서는 일반 인수를 허용하는 추상 클래스 Handler에 대한 익명 클래스를 생성하고 익명 클래스를 생성하는 동안 객체 유형을 전달합니다. 그렇지 않으면 프로그램이 컴파일되지 않으므로 유형 인수를 전달해야 합니다.

public class Tester {
 public static void main(String[] args) {
 // create an Anonymous class to handle 1
 // Here we need to pass Type arguments in diamond operator 
 // before Java 9 otherwise compiler will complain error
 Handler<Integer> intHandler = new Handler<Integer>(1) {
 @Override
 public void handle() {
 System.out.println(content);
 }
 };
 intHandler.handle();
 // create an Anonymous class to handle 2 
 Handler<? extends Number> intHandler1 = new Handler<Number>(2) {
 @Override
 public void handle() {
 System.out.println(content);
 }
 };
 intHandler1.handle();
 Handler<?> handler = new Handler<Object>("test") {
 @Override
 public void handle() {
 System.out.println(content);
 }
 };
 handler.handle(); 
 } 
}
abstract class Handler<T> {
 public T content;
 public Handler(T content) {
 this.content = content; 
 }
 
 abstract void handle();
}

출력

위 프로그램을 컴파일하고 실행해 보면 다음과 같은 결과가 나올 것입니다.

1
2
Test

다이아몬드 연산자 Java 9 이상

Java 9에서는 아래와 같이 익명 클래스와 함께 <> 연산자를 사용할 수 있습니다.

아래 예에서는 유형 인수를 전달할 필요가 없으므로 익명 클래스를 생성하는 동안 일반 인수를 허용하지만 객체 유형 없이 추상 클래스 Handler에 대한 익명 클래스를 생성했습니다. 컴파일러는 유형 자체를 추론합니다.

public class Tester {
 public static void main(String[] args) {
 // create an Anonymous class to handle 1
 // Here we do not need to pass Type arguments in diamond operator 
 // as Java 9 compiler can infer the type automatically
 Handler<Integer> intHandler = new Handler<>(1) {
 @Override
 public void handle() {
 System.out.println(content);
 }
 };
 intHandler.handle();
 Handler<? extends Number> intHandler1 = new Handler<>(2) {
 @Override
 public void handle() {
 System.out.println(content);
 }
 };
 intHandler1.handle();
 Handler<?> handler = new Handler<>("test") {
 @Override
 public void handle() {
 System.out.println(content);
 }
 };
 handler.handle(); 
 } 
}
abstract class Handler<T> {
 public T content;
 public Handler(T content) {
 this.content = content; 
 }
 
 abstract void handle();
}

출력

위 프로그램을 컴파일하고 실행해 보면 다음과 같은 결과가 나올 것입니다.

1
2
Test

java

  1. 자바 슈퍼
  2. 초보자를 위한 Groovy 스크립트 튜토리얼
  3. 자바 주석
  4. 자바 예외
  5. 예제가 있는 Java Reflection API 자습서
  6. 자바 컬렉션 인터페이스
  7. Java의 String Length() 메서드:예제로 찾는 방법
  8. C++ 대 JAVA:차이점은 무엇입니까?
  9. Java 9 - 스트림 API 개선 사항
  10. 자바 대 스칼라:차이점은 무엇입니까?