General method of obtaining

I need help to figure out how to implement a common getter method. Here is the code that I still have:

public class Pair<X extends Comparable<X>, Y extends Comparable<Y>> implements Comparable<Pair<X, Y>>{ private final X first; private final Y second; public GENERIC getX() { return X; } public GENERIC getY() { return Y; } 

Can someone explain to me how to replace GENERIC with some type of returned object <A extends classA> A for this class? I have seen examples of other methods with common return values, but I donโ€™t understand how to apply them here. Thanks!

+4
source share
2 answers

Change

 public GENERIC getX() { return X; } 

to

 public X getX() { return first; } 

extends is the type constraint required on the first call to typemame. The name for this type is the name

+4
source

You have already defined X , and Y are your common types. You just need to specify them in your method signatures. Then return the instance variables as usual. You will also need something to initialize your Pair , such as a constructor (although setter methods will work too):

 public Pair(X x, Y y) { first = x; second = y; } public X getX() { return first; } public Y getY() { return second; } 
+1
source

All Articles