java - Efficiently adding element to the top of the list -


i have enum localfruit can either apple or orange or banana.

public enum fruits {     // can have more elements here     apple, orange, banana;      // code } 

so let's if apple localfruit, orange , banana remotefruits. need shuffle remotefruits , make sure localfruit @ top of list followed remotefruits.

below code doing shuffling , adding original result list: in below code current_fruit can either apple or orange or banana.

private static list<fruits> getfruitsinorder() {     enumset<fruits> localfruit = enumset.of(current_fruit);     enumset<fruits> remotefruits = enumset.complementof(localfruit);      list<fruits> result = new arraylist<fruits>(remotefruits);     collections.shuffle(result);      // first element in list local fruit     result.addall(0, new arraylist<fruits>(localfruit));     return result; } 

since code called lot of times wanted see whether there wrong doing can bottleneck in terms of performance? code ok in terms of performance?

my main goal have localfruit @ top of list, , followed remotefruits (but need shuffle them before adding result list).

all these solutions work hard. java sets pretty efficient, simple array access more so. additionally, building 2 sets (one complement operation), copying arraylist, making new arraylist addall lots of useless work , memory garbage.

the enum gives array of values in order. use it! swap local element position zero, shuffle rest of array. way you're creating 1 data structure: arraylist want return. rest reordering elements.

of course unless have huge enum or calling function millions of times, discussion academic. won't notice performance difference.

import java.util.arrays; import java.util.collections; import java.util.list;  enum fruit { apple, pear, peach, plum, banana }  public class hack {      static list<fruit> getfruitinorder(fruit local) {         list<fruit> list = arrays.aslist(fruit.values());         collections.swap(list, 0, local.ordinal());         collections.shuffle(list.sublist(1, list.size()));         return list;     }      public static void main(string[] args) {         (int = 0; < 10; i++) {             system.out.println(getfruitinorder(fruit.plum));         }     } } 

on macbook:

run: [plum, banana, pear, apple, peach] [plum, peach, pear, apple, banana] [plum, peach, banana, pear, apple] [plum, pear, banana, apple, peach] [plum, pear, apple, banana, peach] [plum, banana, apple, peach, pear] [plum, apple, banana, peach, pear] [plum, apple, peach, pear, banana] [plum, apple, pear, peach, banana] [plum, peach, apple, pear, banana] build successful (total time: 0 seconds) 

Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Website Login Issue developed in magento -

Can the constants be defined inside a model file of a framework in PHP? -