6.7 Outros tipos de referências

Referência a métodos sobrescritos da classe mãe:

Podemos usar super::metodo para referenciar métodos herdados, como:

super::toString;
super::toString;
super::toString;

Enter fullscreen mode Exit fullscreen mode

Referência a métodos estáticos:

Podemos atribuir um método estático a uma interface funcional compatível.
Exemplo com Math::max, que recebe dois inteiros e retorna um inteiro:

BiFunction<Integer, Integer, Integer> max = Math::max;
ToIntBiFunction<Integer, Integer> max2 = Math::max;
IntBinaryOperator max3 = Math::max;
BiFunction<Integer, Integer, Integer> max = Math::max;
ToIntBiFunction<Integer, Integer> max2 = Math::max;
IntBinaryOperator max3 = Math::max;
BiFunction<Integer, Integer, Integer> max = Math::max; ToIntBiFunction<Integer, Integer> max2 = Math::max; IntBinaryOperator max3 = Math::max;

Enter fullscreen mode Exit fullscreen mode

Evitar autoboxing desnecessário:

  • BiFunction: Usa boxing, pois trabalha com Integer.
  • ToIntBiFunction: Reduz umboxing do retorno, pois retorna int.
  • IntBinaryOperator: Evita todo o boxing, pois usa apenas tipos primitivos (int).

Qual usar?

  • IntBinaryOperator é a opção mais eficiente.
  • Porém, a escolha depende do contexto e do método que receberá a lambda como argumento.
  • Muitas vezes, passamos Math::max diretamente sem precisar declarar uma variável.

Conclusão:
Podemos referenciar métodos da classe mãe com super::metodo.
Métodos estáticos podem ser atribuídos a interfaces funcionais compatíveis.
Para operações numéricas, devemos evitar autoboxing usando interfaces específicas para tipos primitivos.

原文链接:6.7 Outros tipos de referências

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享
If you don’t try, you’ll never know. So try.
如果你不去试,你永远也不知道结果,所以去试试吧
评论 抢沙发

请登录后发表评论

    暂无评论内容