0

I'm working on an assignment where I have to sort integers and string type variables.

So I have a method declared as

public void quickSort(ArrayList<Entry<Integer, String>> list) {

but if I want to overload the method and use

public void quickSort(ArrayList<Entry<String, Integer>> list) {

It is recognized as a duplicate.

Is there a way to check what my variable types are? Alternatively, is there a way to sort strings and integers the same way so that I can do something like

public void quickSort(ArrayList<Entry<K, V>> list) {

that will work on both date types?

2 Answers 2

2

You probably need to provide an explicit comparator, since there is no natural ordering of Entrys:

public <T> void quickSort(ArrayList<T> list, Comparator<? super T> comparator)

and then use that comparator inside the method for your comparisons.

The fact that you are trying to sort something with two type parameters (Map.Entry<String, Integer> or Map.Entry<Integer, String>) is not relevant from a generics perspective: it's just a single type, hence you can replace the whole thing with T.

Sign up to request clarification or add additional context in comments.

Comments

1

What also may be helpful for you is that you can check the datatype of a variable with instanceof keyword. E.g.

if (variable instanceof String) { //do stuff }

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.