Home > Java > javaTutorial > What does :: mean in java

What does :: mean in java

下次还敢
Release: 2024-05-09 06:54:18
Original
427 people have browsed it

The double colon (::) symbol in Java represents the following concepts: Static method reference Class method reference Constructor reference Type parameter inference

What does :: mean in java

Double colon (::) in Java

The double colon (::) symbol represents a variety of concepts in the Java language, depending on the context in which it is used.

1. Static method reference

Double colon can be used to obtain a reference to a static method. For example:

<code class="java">List<String> names = List.of("Alice", "Bob", "Carol");
names.forEach(System.out::println);</code>
Copy after login

The above code uses a double colon to reference the System.out.println() static method.

2. Class method reference

Double colon can also be used to obtain a reference to a class method. For example:

<code class="java">class Person {
    public void introduceYourself() {
        System.out.println("Hello, my name is " + name);
    }
}

List<Person> people = List.of(new Person(), new Person());
people.forEach(Person::introduceYourself);</code>
Copy after login

The above code uses a double colon to reference the Person.introduceYourself() class method.

3. Constructor reference

Double colon can also be used to obtain a reference to the constructor. For example:

<code class="java">List<String> names = List.of("Alice", "Bob", "Carol");
Map<String, Integer> nameLengths = names.stream()
    .collect(Collectors.toMap(String::length));</code>
Copy after login

The above code uses a double colon to reference the String() constructor.

4. Type parameter inference

In Java 8 and higher, double colons can be used for type parameter inference. For example:

<code class="java">List<String> names = List.of("Alice", "Bob", "Carol");
Map<String, Integer> nameLengths = names.stream()
    .collect(Collectors.toMap(Function.identity(), String::length));</code>
Copy after login

The above code uses double colons to infer the type parameters of Function.identity() and String::length.

The above is the detailed content of What does :: mean in java. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template