0

i have created many "Vectors" each of this Vectors have his own "Fitness" the fitness is got using a fitness function (already done).
Having for example :

Vector v1 = new Vector();
Vector v2 = new Vector();
V1 = // some data 
V2 = // some other data
double fitness1 = fitness(v1);
double fitness2 = fitness(v2);

now i have hundreds of Vectors and each have it's own fitness, i am trying to create a function called globalbest which returns the Vector having the best fitness but am not always getting the best one !! could anyone help me please ? Here is the code :

   public Vector globalbest(Vector allPopulation) {
    Vector global = new Vector();
    double max = 0;
    for (int i = 0; i < allPopulation.size(); i++) {
        double value = fitness((Vector) allPopulation.get(i));
        if (value > max) {
            global = (Vector) allPopulation.get(i);
            max = value ;
        }
    }
    return global;
}
Ghassen Bellagha
  • 249
  • 3
  • 5
  • 16
  • 2
    Why are you using Vectors? You realize they have been deprecated? – BlackHatSamurai Sep 19 '13 at 23:27
  • @Blaine i just found that they are suitable to my project so i worked with Vectors – Ghassen Bellagha Sep 19 '13 at 23:35
  • why do you have a lot of vectors? use arrayList instead – nachokk Sep 19 '13 at 23:38
  • Why not use a `ArrayList`? See this: http://stackoverflow.com/questions/1386275/why-is-java-vector-class-considered-obsolete-or-deprecated – BlackHatSamurai Sep 19 '13 at 23:40
  • @Blaine But my problem doesn't have any relation with Vectors now don't you think so ?? – Ghassen Bellagha Sep 19 '13 at 23:42
  • No, which is why I'm commenting, rather than answering. It was more of a heads up that Vectors aren't common and have been deprecated. More of an FYI than anything. – BlackHatSamurai Sep 19 '13 at 23:48
  • 1
    @Blaine where are you getting this 'Vectors are deprecated' business from? Not even in Java 8 are they deprecated...and if one needs thread safety, well, ArrayList isn't going to cut it. That said, because of the extra overhead involved with being thread safe and the resulting performance hit, Vectors _are_ out of fashion, which gets us back to Ghassen...Vectors? Why? – Ray Stojonic Sep 20 '13 at 00:18
  • Vectors are not deprecated, they're just pointlessly slow, since every access is synchronized. You don't usually need such behavior, even in multi-threaded environment, so Vectors are not used in real applications. – 9000 Sep 20 '13 at 00:30

1 Answers1

0

If you want the item with the max value from a set of items, something like this will suffice:

Item maxItem = null;
int maxValue = 0;
for( Item item : items ) {
    if( item.value() > maxValue ) {
        maxItem = item;
        maxValue = item.value();
    }
}
return maxItem;
Ray Stojonic
  • 1,260
  • 1
  • 7
  • 11