Re: Using Java Classes to Sort a Small Array Quickly
On 01.09.2011 04:48, KevinSimonson wrote:
I have an<enum> named<ProjectEnum> that has twelve values. Today I
added an instance variable to it, a<String> named<collectionTitle>.
The engineer I'm working with asked me to write a static method in
class<ProjectEnum> that returns an array of<ProjectEnum>s sorted
alphabetically by this value<collectionTitle>.
Since we're talking about an enum and I am sure you made field "name"
final (i.e. to make instances immutable) you can completely ignore sort
performance. You just need to sort once. For example:
package en;
import java.util.Arrays;
import java.util.Comparator;
public enum ProjectEnum {
P1("xyz"), P2("abc"), P3("def");
private final String collectionTitle;
private ProjectEnum(String name) {
if (name == null) {
throw new NullPointerException();
}
this.collectionTitle = name;
}
public String getCollectionTitle() {
return collectionTitle;
}
private static final ProjectEnum[] sortedValues;
static {
sortedValues = ProjectEnum.values();
Arrays.sort(sortedValues, new Comparator<ProjectEnum>() {
@Override
public int compare(ProjectEnum o1, ProjectEnum o2) {
return o1.getCollectionTitle().compareTo(o2.getCollectionTitle());
}
});
}
public static ProjectEnum[] sorted() {
return Arrays.copyOf(sortedValues, sortedValues.length);
}
}
Kind regards
robert
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/