Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Meenachi Suppiah   on Jul 04 In Java Category.

  
Question Answered By: Vonda Ramirez   on Jul 04

The Collections.sort(List list, Comparator c) method requires a object
instance of type Comparator. Putting a string  here named the same as
your Comparator class will not work.

You could do several things one being more flexible but slower and
thrashes more memory the other requiring a present number of
comparators created and stored for later use. You could use a
combination of two schemes mentioned above but I'm not going to
explain that.

Flexible:
Class cClass = Class.forName(request.getParameter("orderBy"));
Comparator comparator = (Comparator) cClass.newInstance();
Collections.sort(AddressArray,comparator);


Preset:
// init
Comparator phoneComparator= new PhoneComparator();
Comparator nameComparator = new NameComparator();

HashMap comparatorMap = new HashMap();
comparatorMap.put ("PHONE",phoneComparator);
comparatorMap.put ("NAME",nameComparator);

// Process
Collections.sort(AddressArray,comparatorMap.get(request.getParameter("orderBy"))\
);

Share: 

 

This Question has 2 more answer(s). View Complete Question Thread

 
Didn't find what you were looking for? Find more on Collections.sort Question Or get search suggestion and latest updates.


Tagged: