Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Collections.sort Question

  Asked By: Meenachi    Date: Jul 04    Category: Java    Views: 7878
  

How do I tell java to use the value of the request.getParameter()
method instead of it treating it like a String? It's seeing the
returned value of request.getParameter as a String(which it is)... I
need it to take the returned value of request.getParameter and use it
as my Comparator's name...

The following needs to translate from this:

Collections.sort(AddressArray, request.getParameter("orderBy"));

to this:

Collections.sort(AddressArray, PHONE_NUMBER);

AddressArray is an ArrayList
PHONE_NUMBER is a Comparator

This allows me to pass in my sort order, but I'm missing something??
Any ideas??

Share: 

 

3 Answers Found

 
Answer #1    Answered By: Vonda Ramirez     Answered 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"))\
);

 
Answer #2    Answered By: Taylor White     Answered On: Jul 04

Collections.sort(AddressArray,
Class.forName(request.getParameter("orderBy")));

This is a potential security hazard, web surfers can load any classes by
altering the parameter name.

If your columns are not dynamic, you might as well just type out the whole
conditions thing.

String orderBy = request.getParameter("orderBy");
orderBy = orderBy == null ? "someDefault" : orderBy.trim(); // Trim, and
NPE prevention
if (orderBy.equals("col1")){
// do sort
} else
if (orderBy.equals("col2")){
// do sort
}
// and so on.

 
Answer #3    Answered By: Cay Nguyen     Answered On: Jul 04

Nevermind a user being able to submit some arbritary name for a class,
if you have some body loading classes on your appserver I think you
have bigger fish to worry about.

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




Tagged: