首頁 > Java > java教程 > 主體

Java中的雙冒號(::)運算符

PHPz
發布: 2023-08-26 13:29:17
轉載
872 人瀏覽過

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 Java 8. It gives a succinct and rich method for alluding to Java 8. It gives a succinct and rich method for alluding to 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 invesgate the language abouttigate the language of adronle, ministraet, formgate the language admingate, ministra un​​y拍, ministraet, formgate the lanc 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 nceinstance v.

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() methodpal recommendf by isPal. 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中的雙冒號(::)運算符的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!