Skip to content
Advertisement

How to implement an increment method on pairs

I am working on a circular linked list and have implemented the following method to increment the elements of the list by a given value.

JavaScript

This method works fine with lists of doubles; however, now I am trying to use it on a list of pairs but I keep getting an error since the method is used for doubles. What should I do to change this method and let it accept pairs and increment them. The following is the pair class I implemented:

JavaScript

Advertisement

Answer

You could introduce an interface Incrementable like this one:

JavaScript

When implementing this interface in Pair the method can be specified as

JavaScript

Please note that the IncrementList(E) method also needs to be changed:

JavaScript

One additional point to consider: should the interface Incrementable return new instances of the same type but with values increased (like BigInteger.add(BigInteger) does) or should the method work with the values in the object itself (like StringBuilder.add(...) does)? It depends on your overall use cases which way to specify this behavior.

The code above assumes that new instances will be used; if you prefer to change the values inside the objects, then the signature in the interface should be void incrementBy(E) and the IncrementList(E) method does not need to re-assign the increased value after applying the increase.

One last thought: to make the IncrementList(E) method work with elements that do not implement Incrementable you can use a helper class with a method that handles some other types of objects, especially Numbers and Strings. As this classes do not support changing their “internal” values, you need to re-assign the result of the increase call to the list elements.

As a starting point, this helper class could look like this:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement