List hashCode() Method in Java with Examples (original) (raw)

Last Updated : 03 Dec, 2024

This method is used to generate the hashCode for the given list.

**Implementation:

Java `

// Java code to show the implementation of // hashCode method in list interface import java.util.*;

public class Main { public static void main(String[] args) {

    // Initializing a list
    List<Integer> l = new ArrayList<>();
    
      // Adding Element
      l.add(1);
    l.add(2);
  
      // Implement hashCode() Method
    int h = l.hashCode();

    System.out.println("HashCode for List : " + h);
}

}

`

**Syntax of Method

int hashCode()

Example of List hashCode() Method

Below programs show the implementation of this method.

**Program 1:

Java `

// Java code to show the implementation of // hashCode method in list interface import java.util.*;

public class Main { public static void main(String[] args) { // Initializing a list of type Linkedlist List l = new LinkedList<>(); l.add(10); l.add(15); l.add(20);

    System.out.println(l);

      // Implementing hashCode() Method
    int h = l.hashCode();

    System.out.println("HashCode of List : " + h);
}

}

`

Output

[10, 15, 20] HashCode of List : 39886

**Program 2: Below is the code to show implementation of list.hashCode() using Linkedlist.

Java `

// Java code to show the implementation of // hashCode method in list interface import java.util.*;

public class Main { public static void main(String[] args) { // Initializing a list of type Linkedlist List l = new LinkedList<>(); l.add("10"); l.add("15"); l.add("20");

    System.out.println(l);

      // Implemented hashCode() Method
    int h = l.hashCode();

    System.out.println("HashCode of List : " + h);
}

}

`

Output

[10, 15, 20] HashCode of List : 1586008

**Reference: Oracle Docs