a只能在这里决赛.为什么?如何a在onClick()不将其保留为私有成员的情况下重新分配方法?
private void f(Button b, final int a){
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
int b = a*5;
}
});
}
Run Code Online (Sandbox Code Playgroud)如何5 * a点击它返回?我的意思是,
private void f(Button b, final int a){
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
int b = a*5;
return b; // but return type is void
}
});
}
Run Code Online (Sandbox Code Playgroud)我不了解lambda的一些事情.
String s = "Hello World";
Function<Integer, String> f = s::substring;
s = null;
System.out.println(f.apply(5));
Run Code Online (Sandbox Code Playgroud)
为什么该f.apply方法仍然有效s = null.毕竟,StringGC应该删除该对象,因为没有指向该对象的指针.
还有一件事,为什么我不需要这里的退货声明?
Function<Integer, String> f = t -> t + "";
Run Code Online (Sandbox Code Playgroud) 什么是第二次s.get()返回"ONE"的解释?
String x = "one";
Supplier<String> s = x::toUpperCase;
System.out.println("s.get() = " + s.get());
x = "two";
System.out.println("s.get() = " + s.get());
Run Code Online (Sandbox Code Playgroud)
更新:
比较它:
String x = "one";
Supplier<String> s = () -> x.toUpperCase();
System.out.println("s.get() = " + s.get());
x = "two";
System.out.println("s.get() = " + s.get());
Run Code Online (Sandbox Code Playgroud)
它会抛出一个编译错误.
考虑以下课程:
class Foo<T> {
void handle(T t) {
System.out.println("handling " + t);
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
Foo<Integer> f = new Foo<>();
list.forEach(f::handle); // compiles fine
//list.forEach(obj -> f.handle(obj));// compilation error
f = new Foo<>(); // reassign f
}
}
Run Code Online (Sandbox Code Playgroud)
为什么我会收到编译错误obj -> f.handle(obj),但不是f::handle?
NullPointerException当我使用方法引用绑定到dog后来分配null给变量的变量时,为什么代码没有抛出?
我正在使用Java 8。
import java.util.function.Function;
class Dog {
private int food = 10;
public int eat(int num) {
System.out.println("eat " + num);
this.food -= num;
return this.food;
}
}
public class MethodRefrenceDemo {
public static void main(String[] args) {
Dog dog = new Dog();
Function<Integer, Integer> function = dog::eat;
dog = null;
// I can still use the method reference
System.out.println("still have " + function.apply(2));
}
}
Run Code Online (Sandbox Code Playgroud) 此代码使用方法引用特定对象的实例方法:
public class Main {
public static void main(String[] args) {
One one=new One();
// F f = ()->{one.bar();}; //previous wrong syntax
F f = one::bar; //4
f.foo();
}
}
class One{void bar(){}}
interface F{void foo();}
Run Code Online (Sandbox Code Playgroud)
我知道它有效.但我无法理解为什么以及如何.
我无法理解的是,该F.foo()方法如何使用对不是方法本身的参数的对象的引用(签名不是void foo(One one)).
我在第4行
F接口的类的实例one对invoke bar()方法的引用来实现该方法但是如何才能foo()有one参考范围?我是否错误地试图将此解决方案转换为"传统的,明确的实现"?如果不是,那么"明确的对应物"是什么?