3

Is there a way to use Java Generics here so my method could take a List<Double> or List<Pair<Double, Double>>?

private Map<Integer, Double> getValuesMap(int indexBegin, int indexEnd, List<Double> values) {
  Map<Integer, Double> map = new LinkedHashMap<>();

  if (indexBegin <= indexEnd) {
    for (int i = indexBegin; i <= indexEnd; i++) {
      map.put(i, values.get(i));
    }
  } else {
    for (int i = indexBegin; i >= indexEnd; i--) {
      map.put(i, values.get(i));
    }
  }

  return map;
}
1
  • 1
    How would you like this List<Pair<Double, Double>> to be handled if it was passed as argument? What should be expected result? Should it be Map<Integer, Pair<Double, Double>> OR Map<Integer, Double> (if yes, then which Double value from Pair<Double, Double> should be used here) OR maybe something else? Commented Nov 23, 2019 at 18:16

1 Answer 1

6

Add generic to your class and use it as below,

public class Test<T> {
private Map<Integer, T> getValuesMap(int indexBegin, int indexEnd, List<T> values) {
        Map<Integer, T> map = new LinkedHashMap<>();

        if (indexBegin <= indexEnd) {
            for (int i = indexBegin; i <= indexEnd; i++) {
                map.put(i, values.get(i));
            }
        } else {
            for (int i = indexBegin; i >= indexEnd; i--) {
                map.put(i, values.get(i));
            }
        }

        return map;
    }

}

Update: You could also use method generic as,

private <T>  Map<Integer, T> getValuesMap(int indexBegin, int indexEnd, List<T> values)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.