Hi,

I have an array, and it must be sorted. The array's objects have associating values.

For example, an array of city details contains these information per object: (String) cityName, (double) cityNumber, (int) cityNumberOfPets.

//e.g.

city[0] = ("Chicago", 243.2, 14);
city[1] = ("New York", 25.3, 15432);
city[2] = ("Dallas", 2.0, 1512);
city[3] = ("Florida", 63.4, 23);

If I were to sort this array by the cityNumber, how would I sort it so that its cityName and cityNumberOfPets are still associated with it?

Any tips would be great.

Have you created a City class yet (attributes name, number, noOfPets)? That's the first stage. Then you can create an array of City's. When you sort that array each City keeps is own name, number etc; there's no risk of them becoming "not associated".

Have you created a City class yet (attributes name, number, noOfPets)? That's the first stage. Then you can create an array of City's. When you sort that array each City keeps is own name, number etc; there's no risk of them becoming "not associated".

Yes i've done what you've mentioned: create a City class, and make multiples of them into an array... but I don't know how to sort them out from there. I know how to sort an array if it just contained, say, ints or Strings, but not when they're objects...?

OK
Look at the Comparator class in the API doc. You create a small Comparator class that compares two City's to say which comes first in the sort order. You can then use a sort method from the Arrays class with that Conparator to sort your array.

To sort in different orders, create a Comparator for each order (eg one that compares the name alphabetically, one that compares the number etc) and pass the appropriate Comparator to the sort method.

This is what I have now:

//...
[INDENT]CityEntry[] information = new CityEntry[numberOfCities];

for(int i = 0; i < numberOfCities; i++){
   //get cityName, cityNumber, cityNumberOfPets.

   information[i] = new CityEntry(cityName, cityNumber, cityNumberOfPets);
}

//Now, I must sort 'information' array, in the ascending order of cityNumber, while keeping  the cityNumber's associative cityName and cityNumberOfPets. How do I do this???


[/INDENT]


///....

class CityEntry{
   public String cityName;
   public double cityNumber;
   public int cityNumberOfPets;

   public CityEntry(String cityName, Double cityNumber, int cityNumberOfPets){
      this.cityName = cityName;
      this.cityNumber = cityNumber;
      this.cityNumberOfPets = cityNumberOfPets;
   }

   public Double [B]getCityNumber[/B](){
      return cityNumber;
   }
}

so now you need to write a Comparator. You'll need get methods in your CityEntry class for any fields you want to use to sort on (eg name).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.