目录
Syntax
语法解释
算法
方法一:使用双冒号操作符的方法引用
Example
Output
Explanation
方法2:使用实例变量使用双冒号运算符进行方法引用
方法3: 使用双冒号运算符引用任意对象的实例方法的方法。
Approach 4: Constructor referencing using double colon operator.
结论
首页 Java java教程 Java中的双冒号(::)运算符

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

Aug 26, 2023 pm 01:29 PM
java 编程 双冒号运算符

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中使用双冒号运算符,请按照以下步骤进行 -

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

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

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

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

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

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

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<Person> 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<String> 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<employee> employeeSupplier = Employee::new;
      Employee employee = employeeSupplier.get();

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

      System.out.println(employee);
   }
}
</employee>
登录后复制

Output

Employee [name=John Doe, age=30]
登录后复制

Explanation

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

结论

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

以上是Java中的双冒号(::)运算符的详细内容。更多信息请关注PHP中文网其他相关文章!

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

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1664
14
CakePHP 教程
1421
52
Laravel 教程
1315
25
PHP教程
1266
29
C# 教程
1239
24
突破或从Java 8流返回? 突破或从Java 8流返回? Feb 07, 2025 pm 12:09 PM

Java 8引入了Stream API,提供了一种强大且表达力丰富的处理数据集合的方式。然而,使用Stream时,一个常见问题是:如何从forEach操作中中断或返回? 传统循环允许提前中断或返回,但Stream的forEach方法并不直接支持这种方式。本文将解释原因,并探讨在Stream处理系统中实现提前终止的替代方法。 延伸阅读: Java Stream API改进 理解Stream forEach forEach方法是一个终端操作,它对Stream中的每个元素执行一个操作。它的设计意图是处

PHP:网络开发的关键语言 PHP:网络开发的关键语言 Apr 13, 2025 am 12:08 AM

PHP是一种广泛应用于服务器端的脚本语言,特别适合web开发。1.PHP可以嵌入HTML,处理HTTP请求和响应,支持多种数据库。2.PHP用于生成动态网页内容,处理表单数据,访问数据库等,具有强大的社区支持和开源资源。3.PHP是解释型语言,执行过程包括词法分析、语法分析、编译和执行。4.PHP可以与MySQL结合用于用户注册系统等高级应用。5.调试PHP时,可使用error_reporting()和var_dump()等函数。6.优化PHP代码可通过缓存机制、优化数据库查询和使用内置函数。7

PHP与Python:了解差异 PHP与Python:了解差异 Apr 11, 2025 am 12:15 AM

PHP和Python各有优势,选择应基于项目需求。1.PHP适合web开发,语法简单,执行效率高。2.Python适用于数据科学和机器学习,语法简洁,库丰富。

PHP与其他语言:比较 PHP与其他语言:比较 Apr 13, 2025 am 12:19 AM

PHP适合web开发,特别是在快速开发和处理动态内容方面表现出色,但不擅长数据科学和企业级应用。与Python相比,PHP在web开发中更具优势,但在数据科学领域不如Python;与Java相比,PHP在企业级应用中表现较差,但在web开发中更灵活;与JavaScript相比,PHP在后端开发中更简洁,但在前端开发中不如JavaScript。

PHP与Python:核心功能 PHP与Python:核心功能 Apr 13, 2025 am 12:16 AM

PHP和Python各有优势,适合不同场景。1.PHP适用于web开发,提供内置web服务器和丰富函数库。2.Python适合数据科学和机器学习,语法简洁且有强大标准库。选择时应根据项目需求决定。

PHP的影响:网络开发及以后 PHP的影响:网络开发及以后 Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

Java程序查找胶囊的体积 Java程序查找胶囊的体积 Feb 07, 2025 am 11:37 AM

胶囊是一种三维几何图形,由一个圆柱体和两端各一个半球体组成。胶囊的体积可以通过将圆柱体的体积和两端半球体的体积相加来计算。本教程将讨论如何使用不同的方法在Java中计算给定胶囊的体积。 胶囊体积公式 胶囊体积的公式如下: 胶囊体积 = 圆柱体体积 两个半球体体积 其中, r: 半球体的半径。 h: 圆柱体的高度(不包括半球体)。 例子 1 输入 半径 = 5 单位 高度 = 10 单位 输出 体积 = 1570.8 立方单位 解释 使用公式计算体积: 体积 = π × r2 × h (4

PHP:许多网站的基础 PHP:许多网站的基础 Apr 13, 2025 am 12:07 AM

PHP成为许多网站首选技术栈的原因包括其易用性、强大社区支持和广泛应用。1)易于学习和使用,适合初学者。2)拥有庞大的开发者社区,资源丰富。3)广泛应用于WordPress、Drupal等平台。4)与Web服务器紧密集成,简化开发部署。

See all articles