Created
September 2, 2022 17:25
-
-
Save ravichandrae/f960e321c48d268d2d53616eb772a08b to your computer and use it in GitHub Desktop.
How to implement our own pair data structure in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashSet; | |
import java.util.Map; | |
import java.util.Objects; | |
import java.util.Set; | |
public class PairsTest { | |
static class IntPair { | |
int x, y; | |
public IntPair(int a, int b) { | |
this.x = a; | |
this.y = b; | |
} | |
@Override | |
public boolean equals(Object o) { | |
IntPair ip = (IntPair) o; | |
return this.x == ip.x && this.y == ip.y; | |
} | |
@Override | |
public int hashCode() { | |
return Objects.hash(this.x, this.y); | |
//return (String.valueOf(this.x) + String.valueOf(this.y)).hashCode(); | |
} | |
} | |
public static void main(String []args) { | |
//Creating a custom pair class is the first choice, because the code is readable | |
//We need to remember implementing the equals and hashCode method. | |
Set<IntPair> intPairs= new HashSet<>(); | |
intPairs.add(new IntPair(0, 1)); | |
intPairs.add(new IntPair(1, 2)); | |
intPairs.add(new IntPair(0, 1)); | |
intPairs.add(new IntPair(0, 2)); | |
for(IntPair pair: intPairs) { | |
System.out.println(pair.x + " " + pair.y); | |
} | |
System.out.println(); | |
//The following approach using arrays does not work and there is no easy way to make it work. | |
/* | |
Set<int[]> intArraySet = new HashSet<>(); | |
int []arr1 = {0, 1}; | |
int []arr2 = {1, 2}; | |
intArraySet.add(new int[]{0, 1}); | |
intArraySet.add(new int[]{1, 2}); | |
intArraySet.add(new int[]{0, 1}); | |
intArraySet.add(arr1); | |
intArraySet.add(arr2); | |
intArraySet.add(arr1); | |
for(int[] pair: intArraySet) { | |
System.out.println(pair[0] + " " + pair[1]); | |
} | |
System.out.println(); | |
*/ | |
//Another way to create a pair is to utilize Map.Entry class in Java standard library | |
Set<Map.Entry<Integer, Integer>> entries = new HashSet<>(); | |
entries.add(Map.entry(0, 1)); | |
entries.add(Map.entry(1, 2)); | |
entries.add(Map.entry(0, 1)); | |
entries.add(Map.entry(0, 2)); | |
for(Map.Entry<Integer, Integer> entry: entries) { | |
System.out.println(entry.getKey() + " " + entry.getValue()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment