tl;dr
record Pair ( String string , State state ) {}
Records
The Answer by Bykov is good if you want a general mutable pair class. Alternatively, you can whip up a specific immutable pairing quite easily in Java 16+ by using the records feature.
A record is a brief way to write a class whose main purpose is to communicate data transparently and immutably. You simply declare the type and name of each member field. The compiler implicitly creates the constructor, getters, equals & hashCode, and toString.
Here is our entire class definition in six words:
record Pair ( String string , State state ) {}
You would of course use more descriptive class and field names.
Instantiate like a conventional class.
Pair p = new Pair( "whatever" , tennessee ) ;
You can declare a record locally, as well as nested or separately.
That record above is equivalent to the conventional code seen below. Modern IDEs such IntelliJ can convert a record to a conventional class, creating this source code.
package work.basil.example;
import java.util.Objects;
public final class Pair {
private final String string;
private final State state;
public Pair ( String string , State state ) {
this.string = string;
this.state = state;
}
public String string () { return string; }
public State state () { return state; }
@Override
public boolean equals ( Object obj ) {
if ( obj == this ) return true;
if ( obj == null || obj.getClass () != this.getClass () ) return false;
var that = ( Pair ) obj;
return Objects.equals ( this.string , that.string ) &&
Objects.equals ( this.state , that.state );
}
@Override
public int hashCode () {
return Objects.hash ( string , state );
}
@Override
public String toString () {
return "Pair[" +
"string=" + string + ", " +
"state=" + state + ']';
}
}