2

I have a table with lat, long, location name. I have calculated the nearest distance from the current location and added the distance in one arraylist and then sorted in ascending order. Next i have added name in other arraylist. Now i need to set the names in the order using the distance from other list. How to do it?

5 Answers 5

3

I think you are using arrays too extensively here. If you have two or more pieces of related data, you should not put each piece into a separate array. Instead create a class to hold all the related data (lat, long, distance and name) and have an array (or some other collection that better meets your needs such as a SortedList) that holds instances of this class. The class could implement Comparable using distance as the measure and therefore allow sorting by distance.

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

Comments

1

are your distances calculated by latitude, longtitude in that table? then why not using a map data structure?

it provides you the pair location-distance

2 Comments

if i put the values in the map then again i need to put them in to a list
i need to calculate distances using those lat, long and add the names in the list using the nearest distance
0

Why not construct directly a TreeMap with the distance as the key and the name as the value. That way they will always be kept sorted by distance.

1 Comment

TreeMap with distance as key is good idea, but what if there are 5 entries with same distance?
0

Presumably you have some class that contains the latitude, longitude and location name. You could put objects of this class into a TreeSet, where the comparator has the current location as constructor arguments, and calculates the distances to do the comparison.

Comments

-1

use Arrays.sort(). You can dont even have to add the distance of each one from current in a separate array. just implement the comparator correctly.

use this after doing a toArray() on your ArrayList.

1 Comment

The point of the question was how to associate an array of names to an array of distances (that has been sorted).

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.