Storing number pairs in java

There are a few options:

Write a custom IntPair class

class IntPair {
  // Ideally, name the class after whatever you're actually using 
  // the int pairs *for.*
  final int x;
  final int y;
  IntPair(int x, int y) {this.x=x;this.y=y;}
  // depending on your use case, equals? hashCode?  More methods?
}

and then create an IntPair[] or a List<IntPair>.

Alternately, create a two-dimensional array new int[n][2], and treat the rows as pairs.

Java doesn't have a built-in Pair class for a few reasons, but the most noticeable is that it's easy enough to write a class that has the same function, but has much more enlightening, helpful names for the class, its fields, and its methods.

If we knew more about what you're actually using this for, we might be able to provide more detailed suggestions -- for all we know, a Map could be appropriate here.


Way 1 : Using javafx.util.Pair class

Pair<Integer> myPair1 = new Pair<Integer>(10,20);
Pair<Integer> myPair2 = new Pair<Integer>(30,40);
HashSet<Pair<Integer>> set = new HashSet<>(); // Java 8 and above
set.add(myPair1);
set.add(myPair2);

Way 2: Using int[] of size 2

int[] myPair1 = new int[] {10,20}; // myPair1[0]=10 , myPair[1] = 20
int[] myPair2 = new int[] {30,40};
HashSet<int[]> set = new HashSet<>(); // Java 8 and above

Way 3 : Converting pair into single number

int myPair1 = 10 * 1000 + 20; 
// int first = myPair1 / 1000; second = myPair2 % 1000;
int myPair2 = 30 * 1000 + 40;
HashSet<Integer> set = new HashSet<>();
set.add(myPair1);
set.add(myPair2);

Way 4 : Using ArrayList instead of int[] in way 2

Way 5 : Custom class that uses HashSet and Pair internally


If you're using JavaFX, you can use the class Pair.

import javafx.util.Pair;

int x = 23;
int y = 98;
        
Pair<Integer, Integer> pair1 = new Pair<>(6, 7);
Pair <Integer, Integer> pair2 = new Pair<>(x, y);

Tags:

Java