0

0

Java中的双冒号(::)运算符

PHPz

PHPz

发布时间:2023-08-26 13:29:17

|

1279人浏览过

|

来源于tutorialspoint

转载

java中的双冒号(::)运算符

In Java, the twofold colon (::) administrator, otherwise called the strategy reference administrator, is a strong element presented in Java 8. It gives a succinct and rich method for alluding to techniques or constructors without conjuring them. This administrator improves on the code and upgrades code coherence, making it an important instrument for designers. In this article, we will investigate the language structure of the twofold colon administrator, talk about its applications, and give code guides to better comprehension.

Syntax

双冒号操作符由两个冒号(::)夹在类名或对象引用和方法名之间。它用作Java中引用方法或构造函数的简写符号。

// A functional interface with a single abstract method
interface Printer {
   void print(String message);
}

// A class that implements the Printer interface
class ConsolePrinter {
   public static void printMessage(String message) {
      System.out.println(message);
   }
}

public class Main {
   public static void main(String[] args) {
      Printer printer = ConsolePrinter::printMessage;
      printer.print("Hello, World!");
   }
}

语法解释

在上面的代码中,我们使用一个名为Printer的实用连接点来定义一个具有单个动态方法print()的类。ConsolePrinter类实现了该连接点,并为printMessage()方法提供了实现。在Principal类中,我们使用双冒号运算符创建了一个Printer实例,以引用ConsolePrinter类的printMessage()方法。最后,我们调用打印机实例的print()方法,该方法又调用printMessage()方法。

算法

  • 要在Java中使用双冒号运算符,请按照以下步骤进行 -

    立即学习Java免费学习笔记(深入)”;

  • 定义一个具有单个抽象方法的函数式接口。

  • 在一个类中实现接口并提供方法的实现。

  • Use the double colon operator to refer to the method or constructor.

  • 使用双冒号操作符创建函数式接口的实例。

  • 在实例上调用该方法,将调用引用的方法或构造函数。

    Peachly AI
    Peachly AI

    Peachly AI是一个一体化的AI广告解决方案,帮助企业创建、定位和优化他们的广告活动。

    下载

方法一:使用双冒号操作符的方法引用

Approach 1 involves using the double colon operator to reference a static method of a class. This approach is useful when we want to pass a method reference that does not depend on any instance variables.

Example

// A functional interface with a single abstract method
interface Calculator {
   int calculate(int a, int b);
}

class MathUtils {
   public static int add(int a, int b) {
      return a + b;
   }
}

public class Main {
   public static void main(String[] args) {
      Calculator calculator = MathUtils::add;
      int result = calculator.calculate(5, 3);
      System.out.println("Result: " + result);
   }
}

Output

Result: 8

Explanation

Calculator是一个具有一个抽象方法calculate()的函数接口。静态的MathUtils函数add()用于相加两个数字。双冒号操作符创建了一个引用MathUtils的add()方法的Calculator实例。我们使用两个数字调用计算器的compute()方法。控制台输出结果。

方法2:使用实例变量使用双冒号运算符进行方法引用

Approach 2 involves using the double colon operator to reference an instance method of a particular object.

Example

import java.util.ArrayList;
import java.util.List;

class Person {
   private String name;

   public Person(String name) {
      this.name = name;
   }

   public void printName() {
      System.out.println(name);
   }
}

public class Main {
   public static void main(String[] args) {
      List persons = new ArrayList<>();
      persons.add(new Person("Alice"));
      persons.add(new Person("Bob"));

      persons.forEach(Person::printName);
   }
}

Output

Alice
Bob

Explanation

在这个例子中,我们有一个Individual类,其中有一个printName()策略,用于打印个体的名字。我们创建了一个Individual项目的列表,并添加了两个示例。使用双冒号运算符,我们在List接口的forEach()方法中引用了Individual类的printName()策略。这会导致printName()方法被调用,打印列表中每个元素的名字到控制台。

方法3: 使用双冒号运算符引用任意对象的实例方法的方法。

Approach 3 involves referencing an instance method of any arbitrary object of a specific type using the double colon operator.

Example

import java.util.Arrays;
import java.util.List;

class StringUtil {
   public boolean isPalindrome(String s) {
      String reversed = new StringBuilder(s).reverse().toString();
      return s.equals(reversed);
   }
}

public class Main {
   public static void main(String[] args) {
      List words = Arrays.asList("level", "hello", "radar", "world");

      StringUtil stringUtil = new StringUtil();
      long count = words.stream().filter(stringUtil::isPalindrome).count();

      System.out.println("Number of palindromic words: " + count);
   }
}

Output

Number of palindromic words: 2

Explanation

In this code scrap, a StringUtil class tests for palindromes with isPalindrome(). We create a list of words and use a stream to sort palindromic words using the isPalindrome() method recommended by the twofold colon administrator. Control center displays palindromic word count.

Approach 4: Constructor referencing using double colon operator.

方法4涉及使用双冒号运算符引用构造函数。

Example

import java.util.function.Supplier;

class Employee {
   public String name;
   public int age;

   public Employee() {
      // Default constructor
   }

   public Employee(String name, int age) {
      this.name = name;
      this.age = age;
   }

   public String toString() {
      return "Employee [name=" + name + ", age=" + age + "]";
   }
}

public class Main {
   public static void main(String[] args) {
      Supplier employeeSupplier = Employee::new;
      Employee employee = employeeSupplier.get();

      employee.name = "John Doe";
      employee.age = 30;

      System.out.println(employee);
   }
}

Output

Employee [name=John Doe, age=30]

Explanation

在这个模型中,我们有一个具有定义构造函数的Representative类。利用双冒号操作符,我们创建了一个引用Representative构造函数的Provider功能交互点的实例。然后,我们调用employeeSupplier实例上的get()方法来获取另一个Representative对象。我们设置了员工的姓名和年龄,并使用toString()方法将其打印到控制台。

结论

Java中的双冒号(::)操作符是Java 8中引入的一个强大元素。它提供了一种简洁而丰富的方式来引用方法或构造函数,而不需要直接调用它们。通过使用双冒号操作符,我们可以改进代码,提高可读性,并利用Java中函数式编程的好处。了解双冒号操作符的语法和不同的使用方法对于每个Java开发者来说都是必要的。因此,请务必在将来的Java项目中探索和使用这个特性,以提升您的编码体验。

相关文章

java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

65

2025.12.31

php网站源码教程大全
php网站源码教程大全

本专题整合了php网站源码相关教程,阅读专题下面的文章了解更多详细内容。

43

2025.12.31

视频文件格式
视频文件格式

本专题整合了视频文件格式相关内容,阅读专题下面的文章了解更多详细内容。

35

2025.12.31

不受国内限制的浏览器大全
不受国内限制的浏览器大全

想找真正自由、无限制的上网体验?本合集精选2025年最开放、隐私强、访问无阻的浏览器App,涵盖Tor、Brave、Via、X浏览器、Mullvad等高自由度工具。支持自定义搜索引擎、广告拦截、隐身模式及全球网站无障碍访问,部分更具备防追踪、去谷歌化、双内核切换等高级功能。无论日常浏览、隐私保护还是突破地域限制,总有一款适合你!

41

2025.12.31

出现404解决方法大全
出现404解决方法大全

本专题整合了404错误解决方法大全,阅读专题下面的文章了解更多详细内容。

204

2025.12.31

html5怎么播放视频
html5怎么播放视频

想让网页流畅播放视频?本合集详解HTML5视频播放核心方法!涵盖<video>标签基础用法、多格式兼容(MP4/WebM/OGV)、自定义播放控件、响应式适配及常见浏览器兼容问题解决方案。无需插件,纯前端实现高清视频嵌入,助你快速打造现代化网页视频体验。

9

2025.12.31

关闭win10系统自动更新教程大全
关闭win10系统自动更新教程大全

本专题整合了关闭win10系统自动更新教程大全,阅读专题下面的文章了解更多详细内容。

8

2025.12.31

阻止电脑自动安装软件教程
阻止电脑自动安装软件教程

本专题整合了阻止电脑自动安装软件教程,阅读专题下面的文章了解更多详细教程。

3

2025.12.31

html5怎么使用
html5怎么使用

想快速上手HTML5开发?本合集为你整理最实用的HTML5使用指南!涵盖HTML5基础语法、主流框架(如Bootstrap、Vue、React)集成方法,以及无需安装、直接在线编辑运行的平台推荐(如CodePen、JSFiddle)。无论你是新手还是进阶开发者,都能轻松掌握HTML5网页制作、响应式布局与交互功能开发,零配置开启高效前端编程之旅!

2

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 0.6万人学习

Node.js 教程
Node.js 教程

共57课时 | 7.8万人学习

CSS3 教程
CSS3 教程

共18课时 | 4.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号