Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!news.albasani.net!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Robert Klemme Newsgroups: comp.lang.java.programmer Subject: Re: Using Java Classes to Sort a Small Array Quickly Date: Thu, 01 Sep 2011 08:32:26 +0200 Lines: 59 Message-ID: <9c8n7tFjhdU1@mid.individual.net> References: <86c4a53b-1ca1-48a8-b954-c01bd449278a@s35g2000prm.googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net Z9xyPnhx+cqAvkGOvng0pQoDm7etoBTEFqac5piXEYH3fj5+E= Cancel-Lock: sha1:5UhR09v/b/HN5tF8s8Bb77IEtkA= User-Agent: Mozilla/5.0 (Windows NT 6.0; WOW64; rv:6.0) Gecko/20110812 Thunderbird/6.0 In-Reply-To: <86c4a53b-1ca1-48a8-b954-c01bd449278a@s35g2000prm.googlegroups.com> Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:7510 On 01.09.2011 04:48, KevinSimonson wrote: > I have an named that has twelve values. Today I > added an instance variable to it, a named. > The engineer I'm working with asked me to write a static method in > class that returns an array ofs sorted > alphabetically by this value. 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() { @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/