I want to use HashMap or any Map for my purpose. I want to define the key
of an element of my Map variable as:
<Intege开发者_开发技巧r, Integer>
Is it possible at Java?
Map<List<Integer>, SomethingElse> aMap =
new HashMap<List<Integer>, SomethingElse>();
You will need to write a class to serve as key to your map. The new class would hold your two integers. Make sure to implement equals() and hashCode() methods.
Probably not the best solution, but you could use Pair(in worth case Point). Check this thread What is the equivalent of the C++ Pair<L,R> in Java?
That's not the way to do this. What I would do is to create some kind of wrapper class that stores two integers, and then instantiate this class as the key of each map entry.
Yes, List
can be key
Yes, you can use a List
as the key to your map.
Caveat: If using a Map
implementation that depends on the result of Object::hashCode
to track the keys, then you must be sure your List
always returns the same hash code value. For a List
, that means all the objects in the list must return the same hash code value, and you cannot be adding or removing objects in the list.
As you can see in the following chart, IdentityHashMap
and EnumMap
are two implementations that do not rely on Object::hashCode
.
Define a class for key
Alternatively, create a class to hold your pair of Integer
objects.
package work.basil.example;
import java.util.Objects;
public class IntegerPair
{
public Integer first, second;
public IntegerPair ( Integer first , Integer second )
{
this.first = Objects.requireNonNull( first );
this.second = Objects.requireNonNull( second );
}
@Override
public boolean equals ( Object o )
{
if ( this == o ) return true;
if ( o == null || getClass() != o.getClass() ) return false;
IntegerPair that = ( IntegerPair ) o;
return first.equals( that.first ) &&
second.equals( that.second );
}
@Override
public int hashCode ( )
{
return Objects.hash( first , second );
}
@Override
public String toString ( )
{
return "IntegerPair{ " +
"first=" + first +
" | second=" + second +
" }";
}
}
Use instances of IntegerPair
as your key to a map.
Map < IntegerPair, String > pairToString = new HashMap <>( 3 );
pairToString.put( new IntegerPair( 10 , 11 ) , "Ones" );
pairToString.put( new IntegerPair( 20 , 21 ) , "Twos" );
pairToString.put( new IntegerPair( 30 , 31 ) , "Threes" );
Dump to console.
System.out.println( "pairToString.toString(): " + pairToString );
pairToString.toString(): {IntegerPair{ first=10 | second=11 }=Ones, IntegerPair{ first=20 | second=21 }=Twos, IntegerPair{ first=30 | second=31 }=Threes}
精彩评论