Creating a User-Defined Printable Pair Class in Java
Last Updated :
16 Nov, 2022
The pair class in C++ Standard Library is used a lot. We can implement our own user-defined pair class in Java and its object can be used anywhere just like any other parameter.
Note :
This class is equivalent to pair<int,int> class in java. You can create your own template or classes for other data types.
Syntax For defining the pair class can be:
class pair{
int first,second;
// constructor for assigning values
pair(int first,int second){
this.first = first;
this.second = second;
}
// function which returns a
pair values(){
return new pair(first,second);
}
// printing the pair class
@Override
public String toString(){
return "("+first+","+second+")";
}
}
- We can now play around with this class and even create an array of pairs, similar to the vector<pair<int,int>> in C++.
Example:
Java
public class pair_example {
public static void main(String[] args)
{
pair[] arr = new pair[ 5 ];
for ( int i = 0 ; i < 5 ; i++) {
arr[i] = new pair(i + 1 , i + 2 );
}
for (pair i : arr) {
System.out.println(i);
}
int value = arr[ 3 ].second;
System.out.println( "Required Value = " + value);
}
}
class pair {
int first, second;
pair( int first, int second)
{
this .first = first;
this .second = second;
}
pair values() { return new pair(first, second); }
@Override public String toString()
{
return first + "," + second;
}
}
|
Output
1,2
2,3
3,4
4,5
5,6
Required Value = 5
Implementation Example:
Suppose we need to store the ith prime number and its index together in a structure.
Java
class GFG {
public static void main(String[] args)
{
int N = 30 ;
java.util.ArrayList<pair> p = new java.util.ArrayList<>();
int index = 1 ;
for ( int i = 1 ; i <= N; i++) {
if (isPrime(i)) {
p.add( new pair(index++, i));
}
}
System.out.println( "i and the ith prime numbers are :" );
System.out.println(p);
}
static boolean isPrime( int n)
{
if (n < 2 )
return false ;
for ( int i = 2 ; i * i <= n; i++) {
if (n % i == 0 )
return false ;
}
return true ;
}
}
class pair {
int first, second;
pair( int first, int second)
{
this .first = first;
this .second = second;
}
pair values() { return new pair(first, second); }
@Override public String toString()
{
return "(" + first + "," + second + ")" ;
}
}
|
Output
i and the ith prime numbers are :
[(1,2), (2,3), (3,5), (4,7), (5,11), (6,13), (7,17), (8,19), (9,23), (10,29)]
Share your thoughts in the comments
Please Login to comment...