2016-02-24 5 views
1

Я нашел этот знак оператора в Java исходного кода здесь весь код, что делает «->» означает, что в Java

/* 
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. 
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. 
* 
*/ 
package java.util.function; 

/** 
* Represents an operation on a single operand that produces a result of the 
* same type as its operand. This is a specialization of {@code Function} for 
* the case where the operand and result are of the same type. 
* 
* <p>This is a <a href="package-summary.html">functional interface</a> 
* whose functional method is {@link #apply(Object)}. 
* 
* @param <T> the type of the operand and result of the operator 
* 
* @see Function 
* @since 1.8 
*/ 
@FunctionalInterface 
public interface UnaryOperator<T> extends Function<T, T> { 

    /** 
    * Returns a unary operator that always returns its input argument. 
    * 
    * @param <T> the type of the input and output of the operator 
    * @return a unary operator that always returns its input argument 
    */ 
    static <T> UnaryOperator<T> identity() { 
     return t -> t; 
    } 
} 

Я гугл и не искать в StackOverflow, но найти ничего, я хочу знать, что знак -> означает

Я нашел этот What does -> means in Java, но я doestn`t подходит мне

---------------- ---- Обновление -----------------------

java -version 
java version "1.8.0_66" 
Java(TM) SE Runtime Environment (build 1.8.0_66-b18) 
Java HotSpot(TM) 64-Bit Server VM (build 25.66-b18, mixed mode) 
+0

версию Java вы используете? – Shriram

+7

Если это jdk8, то это связано с lambda, которое было введено в jdk8 – Shriram

+0

@Shriram updated – Wangbo

ответ

2

То, что вы видите есть выражение Lambda, новая функция, которая была добавлена ​​в Java 8.

Там слишком много говорит о лямбдасе, чтобы все это описать здесь, но, короче говоря, это очень краткий способ добавить анонимный класс, содержащий только один метод.

метод вы упоминаете есть функционально эквивалентны:

static <T> UnaryOperator<T> identity() { 
    return new UnaryOperator<T>{ 
     public T apply(T parameter){ 
     return parameter; 
     } 
    } 
} 

Полный учебник здесь: https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

1

Общий синтаксис,

параметр -> выражение тела

Используя выражение лямбда, вы можете обратиться к конечной переменной или эффективной конечной переменной (которая назначается только один раз).

например:

public class lambdatest{ 

    final static String firstmsg= "Hello! "; 

    public static void main(String args[]){ 
     GreetingService greetService1 = message -> System.out.println(firstmsg+ message); 
     greetService1.sayMessage("am here"); 
    } 

    interface GreetingService { 
     void sayMessage(String message); 
    } 
} 

выход: Привет amhere

+0

Это вряд ли описывается лямбдами; и использование окончательных верификаций вряд ли является характеристикой описания. –

Смежные вопросы