Implementing a Set class

Could someone please show me an example of how to implement the Set Class?
Here's the code for the class:
* @(#)Set.java
package ds.util;
import java.util.*;
* A set is a collection that contains no duplicate elements; that is, sets contain
* no pair of elements obj1 and obj2 such that obj1.equals(obj2). As implied by
* its name, this interface models the mathematical <i>set</i> abstraction.<p>
* The <tt>Set</tt> interface extends the <tt>Collection</tt> interface and
* places additional specification on the  <tt>add</tt> method.
public interface Set<T> extends Collection<T>
     * Returns the number of elements in this set.
     * @return the number of elements in this set.
    int size();
     * Returns <tt>true</tt> if this set contains no elements.
     * @return <tt>true</tt> if this set contains no elements.
    boolean isEmpty();
     * Returns <tt>true</tt> if this set contains the specified element.
     * @param item element whose presence in this set is to be tested.
     * @return <tt>true</tt> if this set contains the specified element.
    boolean contains(Object item);
      * Returns an iterator over the elements in this set.
      * @return an <tt>Iterator</tt> positioned at an element in the set..
    Iterator<T> iterator();
     * Returns an array containing all of the elements in this set.
     * @return an array containing all of the elements in this set.
    Object[] toArray();
    // Modification Operations
     * Adds the specified element to this set if it is not already present.
     * If this set already contains the specified element, the call leaves
     * this set unchanged and returns <tt>false</tt>.
     * @param item element to be added to this set.
     * @return <tt>true</tt> if this set did not already contain the specified
     *         element.
    boolean add(T item);
     * Removes the specified element from this set if it is present. Returns
     * <tt>true</tt> if the set contained the specified element.
     * @param item object to be removed from this set, if present.
     * @return true if the set contained the specified element.
    boolean remove(Object item);
     * Removes all of the elements from this set. This set will be empty after
     * this call returns.
    void clear();
}

What specific trouble are you having?
If we "show you an example of how to implement a Set," we're doing your homework for you. Most here won't do that, and with good reason.

Similar Messages

  • Implementing a secure class loader..

    Hello,
    We have a custom class loader which loads in custom packages from the database or from the file system. We want to ensure that these custom classes do not read or write into the file system. I want to restrict access to these classes when creating them. I read that by setting the proper permissions when defining the class, this could be possible. Here is my implementation of the class loader :
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FilePermission;
    import java.io.IOException;
    import java.net.SocketPermission;
    import java.net.URL;
    import java.security.AccessController;
    import java.security.CodeSource;
    import java.security.PermissionCollection;
    import java.security.Permissions;
    import java.security.PrivilegedExceptionAction;
    import java.security.SecureClassLoader;
    public class TestClassLoader extends SecureClassLoader {
            JarParser jp;
            public TestClassLoader(JarParser jp) {
              super();
                    this.jp = jp;
            public Class findClass(final String name) throws ClassNotFoundException {
                   try {
                       return(Class)
                               AccessController.doPrivileged (
                                     new PrivilegedExceptionAction() {
                                                   public Object run() throws ClassNotFoundException {
                                                         byte[] buf = null;
                                                            try {
                                                               if(jp == null)
                                                                      throw new ClassNotFoundException("Jar file not found");
                                                                    String className = name.replace( '.', '/' ) + ".class";
                                                                    buf = jp.getResource(className);
                                                                    if(buf == null || buf.length == 0)
                                                                          throw new ClassNotFoundException("Class not found");
                                                                    CodeSource cs = getCodeSource(name);
                                                                    return defineClass(name, buf, 0, buf.length, cs);
                                                           catch(Exception e) {
                                                                throw new ClassNotFoundException(name, e);
                   catch(Exception e) {
                        throw new ClassNotFoundException(name, e);
          * @param name
         protected CodeSource getCodeSource(String name) {
                   try {
                       return new CodeSource(new URL("file", "localhost", name), null);
                   catch(Exception e){
                         e.printStackTrace();
                    return null;
            protected PermissionCollection getPermissions(CodeSource cs) {
              PermissionCollection pc = new Permissions();
                    pc.add(new RuntimePermission("exitVM"));
                    pc.add(new FilePermission("${user.home}${/}*", "read"));
                    pc.add(new FilePermission("${user.dir}${/}*", "read"));
             pc.add(new SocketPermission("localhost", "resolve"));
                    return pc;
            public static void main(String[] args) {
                    try {
                       byte[] bytes = new byte[8192];
                      long ttlBytesRead = 0;
                      int noOfBytesToRead = 0;
                            File readFile = new File("test.jar");
                            // "length" here indicates the total no of bytes to read.
                          // This is equal to the file size sans the offset value.
                            long length = readFile.length();
                            Long temp;
                          FileInputStream readFis = null;
                            // Create the RandomAccessFile
                      try{
                                 readFis = new FileInputStream(readFile);
                           catch(Exception e) {
                                throw new IOException(e.getMessage());
                           long tempLong;
                      StringBuffer buffer = new StringBuffer();
                            do {
                                if ((length - ttlBytesRead) > 8192)
                                         tempLong = 8192;
                                    else
                                        tempLong = (length - ttlBytesRead);
                                 temp = new Long((length - ttlBytesRead) > 8192 ? 8192 : (length - ttlBytesRead));
                                   noOfBytesToRead = temp.intValue();
                                  if(noOfBytesToRead == 0)
                                            break;
                              // Read the specified no of bytes into the byte
                                    // array from the file.
                             try {
                                       readFis.read(bytes,0,noOfBytesToRead);
                                   catch(Exception e1) {
                                       throw new IOException(e1.getMessage());
                                   String str  = new String(bytes, 0, noOfBytesToRead);
                                buffer.append(str);
                                    ttlBytesRead += noOfBytesToRead;
                            } while(ttlBytesRead < length);
                     try {
                               readFis.close();
                           catch(Exception e1) {}
                            JarParser jp = new JarParser("test.jar", buffer.toString().getBytes());
                     TestClassLoader tcl = new TestClassLoader(jp);
                      Class class1 = tcl.findClass("com.test.TestFileWrite");
                     Object obj = class1.newInstance();
                   catch(Exception e) {
                        e.printStackTrace();
    }JarParser is the class which parses through the jar file and caches the contents as bytes.
    The test.jar contains a single class which writes into the user's home directory. As you can see, I have granted only read access on the home dir.
    When I run this however, the newly loaded class does manage to write into the file system with no problems. Is there anything further that I need to do to enable restriction on the file system ?
    Thanks.

    If I've been reading correctly, they don't want you
    subclassing SecurityManager for security any more.
    Everything should be handled by the AccessController
    using Permission objects. The easiest way to configure
    the AccessController is through policy files.erg. where did you read this? I checked the 1.5.0 beta API just now, and nothing is officially deprecated.
    :{  I don't have time to figure out the AccessController API right now.
    I have yet to find a good tutorial on the matter of
    security and classloaders. If anyone has a good
    reference, it would be much appreciated.I second that.
    And as a temporary solution (because we're already behind schedule), I went ahead and wrote my own SecurityManager, using the ideas I mentioned above.
    I'm posting it at the site below in case anyone can offer any feedback (such as pointing out fatal weaknesses). We tried yesterday for an hour or so to break it, and it withstood all our tests; but security is not our specialty, so there's probably room for improvement.
    (I'd post it in this message, but it's a wee bit large.)
    www.personal.utulsa.edu/~jeremy-wood/software/ThreadBasedSecurityManager.java
    (And if it passes your scrutiny and looks useful, feel free to use it. But note the disclaimers.)

  • Instance of one of implementations of abstract class depending on context??

    Hi all,
    I just wonder if it is possible in Java to call creation of a new instance of an implementation of an abstract class depending on context.
    I mean something like:
    abstract class Abstract
    //1st implementation of Abstract class
    class Concrete1 extends Abstract
    //2nd implementation of Abstract class
    class Concrete2 extends Abstract
    }And now, somewhere else in the code, I would really need to call something like this:
    Abstract test1 = new ...(); //here I need sometimes to be created instance of Concrete1, sometimes instance of Concrete2
    Is there a way how to do this??

    Some more concrete code if it helps:
    Abstract class:
    * Individual.java
    * Created on 21. leden 2007, 1:08
    package genetics;
    * Abstract class defining fields and methods of one individual for genetic algorithms
    * This class is supposed to be implemented according to problem to be solved
    * @author Richard V�tek
    * @version 1.0
    abstract public class Individual implements Comparable<Individual>
       * Create random chromosomes for this individual
      protected abstract void createRandomChromosomes();
       * Count fitness of this individual
       * This number says how good is this individual (the higher number the better).
       * Better fitness means that this individual is closer to solution.
       * @return  int   Fitness of this individual
      protected abstract int getFitness();
       * Cross-breed this individual with another individual
       * This leaves untouched number of chromosomes to certain (randomly generated) position.
       * From this position on, it will swap chromosomes between this and another individual.
       * So this individual gets changed (cross-breeded) as well as the other, which is returned
       * as result of this method.
       * @param   other              The other individual to cross-breed with
       * @return  Individual         Hybrid of this and another individual (in fact, the other individual
       *                             after cross-breed (this (source) individual gets changed too after cross-breed)
      protected abstract Individual crossbreed(Individual other);
       * Mutate this individual
       * Mutate chromosomes of this individual; every chromosome is mutated
       * with probability set in settings of evolution.
       * This probability is supposed to be quite low number, roughly 1 %.
      protected abstract void mutate();
       * Check this individual
       * Check if this individual still suits the assignment.
       * If not, repair this individual to suit it again.
      protected abstract void check();
       * Implementation of Comparable: comparing of individuals by fitness
       * @param other Another individual to compare
      public int compareTo(Individual other)
        return this.getFitness() - other.getFitness();
    One implementation class:
    * KnapsackIndividual.java
    * Created on 21. leden 2007, 1:41
    package genetics;
    import java.util.Random;
    import java.util.TreeMap;
    import knapsack.KnapsackProblem;
    * This is practically the same as KnapsackProblem class but designed specially
    * for solving knapsack problem with genetic algorithm so all unnecessary fields
    * and methods are removed.
    * @author Richard V�tek
    * @version 1.0
    public class KnapsackIndividual extends Individual
       * Chromosomes of this individual
       * In case of knapsack problem, they are things currentl in knasack
      protected boolean[] arrChromosomes;
       * Cached value of fitness of this individual
       * Used to not to count fitness of this individual everytime when needed
       * (and it is often needed); once counted, it will be read from this cached value
      private int intFitnessCache = Integer.MIN_VALUE;
       * Randomizer for random-driven methods (like mutation, etc.)
      private Random randomizer = new Random();
       * Reference to evolution to read mutation probability from
      protected Evolution evolution;
       * Assignment of problem instance
      protected KnapsackProblem assignment;
       * Create a new Individual instance
       * @param   assignment  Object representing assignment of particular problem
       * @param   evolution   Reference to evolution object to be able to read evolution's settings from
      public KnapsackIndividual(KnapsackProblem assignment, Evolution evolution)
        this.assignment = assignment;
        this.evolution = evolution;
        this.arrChromosomes = new boolean[assignment.getNumberOfThings()];
       * Create random chromosomes for this individual
       * @see Individual#createRandomChromosomes()
      protected void createRandomChromosomes()
        int intChromosomeCount = this.arrChromosomes.length;
        for (int i = 0; i < intChromosomeCount; i++)
          this.arrChromosomes[i] = this.randomizer.nextBoolean();
       * Get fitness of this individual
       * In case of knapsack, fitness is sum of prices of all things currently in knapsack
       * @see Individual#getFitness()
      protected int getFitness()
        //if cached value exist, return it
        if (this.intFitnessCache != Integer.MIN_VALUE)
          return this.intFitnessCache;
        //otherwise, count fitness of this individual
        int intChromosomeCount = this.arrChromosomes.length;
        int intSumOfValues = 0;
        //in case of knapsack, fitness is value of all things currently in knapsack
        //(sum of values of all things in knapsack)
        for (int i = 0; i < intChromosomeCount; i++)
          intSumOfValues = this.assignment.arrPrices;
    //save counted fitness to cache
    this.intFitnessCache = intSumOfValues;
    return intSumOfValues;
    * Cross-breed two individuals
    * @param other The other individual for cross-breed
    * @return The other individual after cross-breed (but this individual is affected too)
    * @see Individual#crossbreed()
    protected Individual crossbreed(Individual other)
    int intChromosomeCount = this.arrChromosomes.length;
    //position from which on swap chromosomes of this and the other individual
    int intCrossbreedPosition = this.randomizer.nextInt(intChromosomeCount);
    boolean booTemp;
    //swap chromosomes from cross-breed position on
    for (int i = intCrossbreedPosition; i < intChromosomeCount; i++)
    booTemp = ((KnapsackIndividual) this).arrChromosomes[i];
    ((KnapsackIndividual) this).arrChromosomes[i] = ((KnapsackIndividual) other).arrChromosomes[i];
    ((KnapsackIndividual) other).arrChromosomes[i] = booTemp;
    return other;
    * Mutate individual chromosomes of this individual with certain probability
    * In case of knapsack, particular thing is just inserted/taken out of the knapsack
    * @see Individual#mutate()
    protected void mutate()
    //probability of mutation (in percents)
    int intMutationProbability = this.evolution.getMutationProbability();
    int intChromosomeCount = this.arrChromosomes.length;
    //iterate through all chromosomes, mutating them with certain (set) probability
    for (int i = 0; i < intChromosomeCount; i++)
    //mutation probability passed => mutate this chromosome
    if (this.randomizer.nextInt(100) < intMutationProbability)
    this.arrChromosomes[i] = !this.arrChromosomes[i];
    //when mutation finished, we must check if this individual still suits the assignment;
    //if not, repait it
    this.check();
    * Check if this individual still suits the assignment; if not, repair it
    * In case of knapsack it means that sum of weights of things currently in knapsack
    * will not exceed capacity of backpack; if exceeds, take out as many things as necessary
    * to not to exceed again; choose things to be taken out according to worst weight to price ratio
    * @see Individual#check()
    protected void check()
    int intSumOfWeights = 0;
    //list of things in the knapsack sorted by weight to price ratio
    //key: index of thing in knapsack
    //value: weight/price ratio
    TreeMap<Integer, Float> things = new TreeMap<Integer, Float>();
    for (int i = 0; i < this.arrChromosomes.length; i++)
    //thing in the knapsack
    if (this.arrChromosomes[i] == true)
    //add its weight to sum of weights
    intSumOfWeights += this.assignment.arrWeights[i];
    //add it to the list of things sorted by weight to price ratio
    things.put(i, (((float) this.assignment.arrWeights[i]) / ((float) this.assignment.arrPrices[i])));
    //sum of weights exceeds knapsack capacity => take out as many things as necessary
    while (intSumOfWeights > this.assignment.getKnapsackCapacity())
    //take out thing with worst weight/price ratio from all things currently in knapsack
    this.arrChromosomes[things.lastKey()] = false;
    //update sum of weights of things currently in knapsack
    intSumOfWeights -= things.get(things.lastKey());
    //also remove this thing from list of things
    things.remove(things.lastKey());
    And another class, where i need this feature (tried to use generics for that, but they can't be used in this way):
    * Evolution.java
    * Created on 21. leden 2007, 2:47
    package genetics;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Arrays;
    * Class for algorithms using simulated evolution to deal with a problem
    * Tried to be designed general enough to allow to be used for every genetic algotihm.
    * If true, only class Individual must be implemented according to problem to be solved,
    * the rest of genetic algorithm stays the same.
    * @author Richard V�tek
    * @version
    public class Evolution<Problem, IndividualClass extends Individual>
       * Number of generations of evolution to finish
      protected int intGenerationCount;
       * Number of individuals in each generation
      protected int intGenerationSize;
       * Elite individual count
       * All elite individuals are just copied from one generation to another with no change
      protected int intGenerationEliteCount;
       * Number of individuals participating a tournament
       * To select an good individual for next generation, tournaments are hold.
       * This affects number of individuals which one good individual is selected
       * from in one tournament.
       * @see <a href="http://cs.felk.cvut.cz/%7Exobitko/ga/example_f.html">Genetic Algorithm Example Applet</a>
      protected int intGenerationTournamentSize;
       * Probability of mutation (in percents)
      protected int intMutationProbability;
       * Current generation of individuals in evolution
      protected Generation<IndividualClass> thisGeneration;
       * Next generation of individuals in evolution
      protected Generation<IndividualClass> nextGeneration;
       * Fitness of best individual in this generation
      private int intIndividualBestFitness;
       * Sum of fitnesses of all individuals in this generation
      private int intIndividualsSumFitness;
       * Fitness of worst individual in this generation
      private int intIndividualWorstFitness;
       * Fitness of best elite individual in (every) generation
       * Auxilliary variable to not to count statistics for elite individuals
       * in each generation as well (not needed - elite individuals don't change themselves)
      private int intIndividualEliteBestFitness;
       * Sum of fitnesses of all elite individuals in (every) generation
       * Auxilliary variable to not to count statistics for elite individuals
       * in each generation as well (not needed - elite individuals don't change themselves)
      private int intIndividualElitesSumFitness;
       * Fitness of worst elite individual in (every) generation
       * Auxilliary variable to not to count statistics for elite individuals
       * in each generation as well (not needed - elite individuals don't change themselves)
      private int intIndividualEliteWorstFitness;
       * Create a new instance of Evolution (settings passed through parameters)
       * @param   intGenerationCount            Number of generation of evolution to finish
       * @param   intGenerationSize             Number of individuals in each generation
       * @param   intGenerationEliteRatio       Elite individuals to generation size ratio (in percents)
       * @param   intGenerationTournamentRatio  Members of tournament to generation size ratio (in percents)
       * @param   intMutationProbability        Probability of mutation of each chromosome of each individual of generation (in percents)
       * @see     #intGenerationEliteCount
       * @see     #intGenerationTournamentSize
      public Evolution(
        int intGenerationCount, int intGenerationSize,
        int intGenerationEliteRatio, int intGenerationTournamentRatio,
        int intMutationProbability)
        this.intGenerationCount = intGenerationCount;
        this.intGenerationSize = intGenerationSize;
        this.intGenerationEliteCount = (int) (intGenerationSize * (intGenerationEliteRatio / 100.0));
        this.intGenerationTournamentSize = (int) (intGenerationSize * (intGenerationTournamentRatio / 100.0));
        this.intMutationProbability = intMutationProbability;
       * Create a new instance of Evolution (settings loaded from settings file)
       * @param   strSettingFile  Name of file containing settings for evolution
       * @throws  IOException     File does not exist, cannot be read, etc.
       * @throws  Exception       Another exception occured during loading of file
      public Evolution(String strSettingFile)
        BufferedReader settings;
        String settingsLine;
        int intLineCounter = 0;
        int intSetting;
        try
          settings = new BufferedReader(new FileReader(strSettingFile));
          while ((settingsLine = settings.readLine()) != null)
            intLineCounter++;
            settingsLine = settingsLine.substring(0, settingsLine.indexOf("\t"));
            intSetting = Integer.parseInt(settingsLine);
            switch (intLineCounter)
              case 1:
                this.intGenerationCount = intSetting;
                break;
              case 2:
                this.intGenerationSize = intSetting;
                break;
              case 3:
                this.intGenerationEliteCount = (int) (this.intGenerationSize * (intSetting / 100.0));
                break;
              case 4:
                this.intGenerationTournamentSize = (int) (this.intGenerationSize * (intSetting / 100.0));
                break;
              case 5:
                this.intMutationProbability = intSetting;
                break;
            } //switch
          } //while
          //after reading has been completed, let's close the stream
          settings.close();
        } //try
        //IO exception - file not found, cannot be read, etc.
        catch (IOException ioe)
          System.out.println("Vyskytl se I/O probl�m p&#345;i na&#269;�t�n� zad�n� ze souboru " + strSettingFile);
        //Exception - another problem during reading of file
        catch (Exception e)
          System.out.printf("Vyskytl se n&#283;jak� divn� probl�m p&#345;i na&#269;�t�n� zad�n� ze souboru %s. V�pis vyj�mky:\n", strSettingFile);
          e.printStackTrace();
       * Vivify first generation for evolution
       * Necessary number of individuals is created with random chromosomes.
       * Their chromosomes must then be checked if they suit the assignment
       * and if not so, repaired.
      private Generation<IndividualClass> vivifyFirstGeneration()
        //create a brand-new generation
        Generation generation = new Generation<IndividualClass>(this);
        int intTemp;
        //for all individual of this generation
        for (int i = 0; i < this.intGenerationSize; i++)
    //create an individual with no chromosomes
    generation.arrIndividuals[i] = new IndividualClass(this, Problem);
          //create a set of random chromosomes
          neration.arrIndividuals.createRandomChromosomes();
    //if these chromosomes does not suit assignment, repair them
    generation.arrIndividuals[i].check();
    //sort Individuals by fitness so elite individuals get to first positions of array
    Arrays.sort(generation.arrIndividuals);
    //now count statistics for elite individuals (it is enough to count them once,
    //elite don't get changed so their statistics don't get changed either)
    this.intIndividualEliteBestFitness = Integer.MIN_VALUE;
    this.intIndividualElitesSumFitness = 0;
    this.intIndividualEliteWorstFitness = Integer.MAX_VALUE;
    //count statistics for elite individuals
    for (int i = 0; i < this.intGenerationEliteCount; i++)
    intTemp = generation.arrIndividuals[i].getFitness();
    //better fitness than best fitness so far
    if (intTemp > this.intIndividualEliteBestFitness)
    this.intIndividualEliteBestFitness = intTemp;
    //worse fitness than worst fitness so far
    else if (intTemp < this.intIndividualEliteWorstFitness)
    this.intIndividualEliteWorstFitness = intTemp;
    this.intIndividualElitesSumFitness += intTemp;
    //reset generation's statistics
    this.intIndividualBestFitness = this.intIndividualEliteBestFitness;
    this.intIndividualsSumFitness = this.intIndividualElitesSumFitness;
    this.intIndividualWorstFitness = this.intIndividualEliteWorstFitness;
    //count generation's statistics also from rest of individuals
    for (int i = this.intGenerationEliteCount; i < this.intGenerationSize; i++)
    updateGenerationStatistics(generation.arrIndividuals[i].getFitness());
    return generation;
    * Get next generation in evolution
    * Core method for all evolution; Through this method, new generation is obtained.
    * Every next generation should contain better individuals than the previous one
    * (till certain point) so with growing number of iterations in evolution, we
    * get better results (till certain point).
    * Everytime all elite individuals are copied to next generation, then hold needed number of
    * tournaments to choose a pair of good-looking individuals, cross-breed individuals in these
    * pairs, mutate them (and repair if necessary) and finally add to next generation.
    * @return Generation Next generation in evolution
    * @see Generation#tournament()
    * @see Generation#crossbreed()
    * @see Generation#mutate()
    private Generation getNextGeneration()
    Generation nextGeneration = new Generation(this);
    //number of pairs of individuals to select for next generation
    int intIndividualPairsToSelect = (this.intGenerationSize - this.intGenerationEliteCount) / 2;
    int intTemp;
    //reset generation's statistics
    this.intIndividualBestFitness = this.intIndividualEliteBestFitness;
    this.intIndividualsSumFitness = this.intIndividualElitesSumFitness;
    this.intIndividualWorstFitness = this.intIndividualEliteWorstFitness;
    //just copy all elite individuals from this generation to another
    //(they are on first positions of array of individuals)
    for (int i = 0; i < this.intGenerationEliteCount; i++)
    nextGeneration.arrIndividuals[i] = this.thisGeneration.arrIndividuals[i];
    //hold as many tournaments as necessary to select remaining number of pairs
    //of good-looking individuals for next generation (apart from the elite ones)
    for (int i = 0; i < intIndividualPairsToSelect; i++)
    this.thisGeneration.tournament();
    this.thisGeneration.crossbreed();
    this.thisGeneration.mutate();
    //add this individual in next generation
    nextGeneration.arrIndividuals[2 * i] = this.thisGeneration.nextGenerationIndividual01;
    //update statistics of generation
    updateGenerationStatistics(this.thisGeneration.nextGenerationIndividual01.getFitness());
    //add this individual in next generation
    nextGeneration.arrIndividuals[2 * i + 1] = this.thisGeneration.nextGenerationIndividual02;
    //update statistics of generation
    updateGenerationStatistics(this.thisGeneration.nextGenerationIndividual02.getFitness());
    //next generation is complete => return it
    return nextGeneration;
    * Update statistics of current generations
    * @param intFitness Fitness that may possibly update generation's statistics
    * (best fitness, worst fitness, sum of fitnesses)
    private void updateGenerationStatistics(int intFitness)
    //better fitness than best fitness so far
    if (intFitness > this.intIndividualBestFitness)
    this.intIndividualBestFitness = intFitness;
    //worse fitness than worst fitness so far
    else if (intFitness < this.intIndividualWorstFitness)
    this.intIndividualWorstFitness = intFitness;
    //update sum of fitnesses as well (for average fitness)
    this.intIndividualsSumFitness += intFitness;
    * Execute evolution process
    * Vivify first generation and then as many next generations as set in settings of evolution
    public void evolution()
    this.thisGeneration = vivifyFirstGeneration();
    //output generation's statistics
    System.out.printf("Generace 0:\t%d\t%d\t%d", this.getIndividualBestFitness(), this.getIndividualAverageFitness(), this.getIndividualWorstFitness());
    for (int i = 0; i < this.intGenerationCount; i++)
    this.nextGeneration = getNextGeneration();
    this.thisGeneration = this.nextGeneration;
    //output generation's statistics
    System.out.printf("Generace %d:\t%d\t%d\t%d", i, this.getIndividualBestFitness(), this.getIndividualAverageFitness(), this.getIndividualWorstFitness());
    * Get best fitness of all individuals in this generation
    public int getIndividualBestFitness()
    return intIndividualBestFitness;
    * Get average fitness of all individuals in this generation
    public float getIndividualAverageFitness()
    return (this.intIndividualsSumFitness / (float) this.intGenerationSize);
    * Get worst fitness of all individuals in this generation
    public int getIndividualWorstFitness()
    return intIndividualWorstFitness;
    * Get probability of mutation
    * @return Probability of mutation of each chromosome of every individual in generation (in percents)
    public int getMutationProbability()
    return intMutationProbability;

  • HashCode on implementation of Set

    javadoc on Set<E> hashcode:
    "int hashCode()
    "Returns the hash code value for this set. The hash code of a set is defined to be the sum of the hash codes of the elements in the set, where the hashcode of a null element is defined to be zero. This ensures that s1.equals(s2) implies that s1.hashCode()==s2.hashCode() for any two sets s1 and s2, as required by the general contract of the Object.hashCode method."
    Let's say I have a class Foo which is an implementation of Set<Bar>. Bar's hashCode is a perfect hash. But the sum of such hash codes won't be a perfect hash on Foo instances, and I'd like to have Foo's hashCode return a perfect hash. (A perfect hash is possible given the domain of Bar instances). If Foo's hashCode returns a value which meets the assurance stated in the doc, but is not the sum of the element hash codes, do I cause a potential client problem by violating what the hash code is "defined to be"?

    In addition to the excelent advice jverd gave I'd
    like to ask if beeing a Set<Bar> is Foo's primary
    job. Do clients view it as anything else, than a
    Set<Bar>? (If it's usually referenced from a
    variabled delcard "Foo foo;" and not "Set<Bar> foo",
    then chances are, that beeing a Set is not it's
    primary job).Yes, being a Set<Bar> is its primary, and probably only, job. The name of the class is (the equivalent of) BarSet.
    >
    If indeed Foo "is" "not just" a Set<Bar>, then you
    might want to remove that interface from it and
    produce a delegate, that acts as the Set.
    (foo.getSet())
    This way you could implement hashCode() of Foo the
    perfect way you want it to and have
    foo.getSet().hashCode() follow the requirements laid
    out by Set.hashCode()).
    This way you could fullfill both requirements.Or, as kajbj implies, I could fulfill both by just supplying a perfectHashCode(). I like that idea.
    Message was edited by:
    com.stevebrecher to correct misspelling of a name

  • Implement extendable set of constants

    Hi!
    I am trying to figure out what would be a suitable way of implementing a set of default constants that should be possible to extend with custom ones. I am creating an API that will have several sets of constant values but the user of the API should be able to extend/register/add additional constants to these sets. In my first attempt I have been looking at the enum type but its not straight forward to use enums since they cannot be extended. One solution that I discovered elsewhere was to define an interface for the constants and let the enum implement that interface. However I am not really sure I understand how this should look.
    It would be great with some code examples on the enum solution mentioned above. Other suggestions are also appreciated!

    Encephalopathic, thats a good question.
    I guess it is because they actually are constants in the API and I want the user to treat them as constants.What do you mean in the part I underlined?
    There are lots of ways to prevent the user to change a reference (the surest one being not to expose it at all, more on that later).
    Moreover the user should have easy access to the values (like Substance.PO4).Which your DefaultSubstance attempt above achieves.
    I also want to prevent multiple instances of the same value (substance).Can you elaborate why?
    Often this "need" to have only one instance is overrated (if not plain wrong). For the occasions where it is valid (and countless discussions on whether it is or isn't), you can look at the Singleton design pattern, and the (unofficial name but easily derived) multiton variant.
    Let's say that I implement a simple Substance class and then a DefaultSubstances class that defines the default set of values:Fine sketch.
    It feels like I do not have enough control when the user subclass this class to implement new constants.Which kind of "control" do you want?
    Most of what I can imagine can be achieved by doing checks in the constructor of a root superclass, e.g. Substance (if a user subclasses the class, the compiler/JVM will make sure his constructor invokes yours). e.g. if you want to make sure no-one redefines a substance named "PO4" that's easily done in the superclass' constructor.
    And how do I make this class and all subclasses iterable over all defined constants?The root superclass can maintain a private static map of all known substances, populated by the constructor.
    Remember the point about not exposing the reference? Well the root superclass could expose the known substances via a method call:
    Substance po4 = Substance.get("PO4");
    Perhaps it would be a good soultion to give up the enum classNot necessarily. But you sure can't extend enums, so you'd have to define an interface, as Joachim demonstrated; but with an interface you don't have the "veto" power of a mandatory superconstructor.
    In general: can you elaborate on what the Substance class does? Which methods does it expose (you know enums can expose methods)?
    How is it used (e.g. switch statements).
    It is also possible that the code might be refactored into something completely different, leveraging polymorphism instead of if/switch based on constants, but that depends on the usage.
    Edited by: jduprez on Mar 1, 2010 12:18 PM

  • Implementing constructor outside class implementation..

    REPORT  ZTUSH.
    CLASS counter DEFINITION.
      PUBLIC SECTION.
        METHODS CONSTRUCTOR.
        CLASS-METHODS: set IMPORTING value(set_value) TYPE i,
                 increment,
                 get EXPORTING value(get_value) TYPE i.
       PRIVATE SECTION.
       CLASS-DATA count TYPE i.
    ENDCLASS.
    METHOD CONSTRUCTOR.
    WRITE:/ 'I AM CONSTRUCTOR DUDE'.
    ENDMETHOD.
    CLASS counter IMPLEMENTATION.
    METHOD set.
        count = set_value.
      ENDMETHOD.
    ENDCLASS.
    DATA cnt TYPE REF TO counter.
    START-OF-SELECTION.
      CREATE OBJECT cnt.
      CALL METHOD counter=>set EXPORTING set_value = number.
    I THOUGHT WE CAN DEFINE CONSTRUCTOR METHOD OUTSIDE CLASS IMPLEMENTATION AS IN JAVA. But when I do that I get an error, method can be implemented only withing class. Why?

    Hello Rajesh
    I do not fully understand what you mean by "I THOUGHT WE CAN DEFINE CONSTRUCTOR METHOD OUTSIDE CLASS IMPLEMENTATION AS IN JAVA". However, if you mean that we can create an object without having an explicit CONSTRUCTOR method defined then this is possible in ABAP like in Java (see coding below).
    Regards
      Uwe
    REPORT ztush.
    *       CLASS counter DEFINITION
    CLASS counter DEFINITION.
      PUBLIC SECTION.
    *METHODS CONSTRUCTOR.
        CLASS-METHODS: set IMPORTING value(set_value) TYPE i,
        increment,
        get EXPORTING value(get_value) TYPE i.
      PRIVATE SECTION.
        CLASS-DATA count TYPE i.
    * NO explicit constructor
    *METHOD CONSTRUCTOR.
    *WRITE:/ 'I AM CONSTRUCTOR DUDE'.
    *ENDMETHOD.
    ENDCLASS.                    "counter DEFINITION
    *       CLASS counter IMPLEMENTATION
    CLASS counter IMPLEMENTATION.
      METHOD set.
        count = set_value.
      ENDMETHOD.                    "set
      METHOD get.
      ENDMETHOD.                    "get
      METHOD increment.
      ENDMETHOD.                    "increment
    ENDCLASS.                    "counter IMPLEMENTATION
    DATA cnt TYPE REF TO counter.
    START-OF-SELECTION.
    * Implicit constructor is called
      CREATE OBJECT cnt.
      CALL METHOD counter=>set
        EXPORTING
          set_value = 5.
    END-OF-SELECTION.

  • How to implement a java class in my form .

    Hi All ,
    I'm trying to create a Button or a Bean Area Item and Implement a class to it on the ( IMPLEMENTATION CLASS ) property such as ( oracle.forms.demos.RoundedButton ) class . but it doesn't work ... please tell me how to implement such a class to my button .
    Thanx a lot for your help.
    AIN
    null

    hi [email protected]
    tell me my friend .. how can i extend
    the standard Forms button in Java ? ... what is the tool for that ... can you explain more please .. or can you give me a full example ... i don't have any expereience on that .. i'm waiting for your reply .
    Thanx a lot for your cooperation .
    Ali
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by [email protected]:
    Henrik, the Java importer lets you call Java classes on the app server side - I think what Ali is trying to do is integrate on the client side.
    If you want to add your own button then if you extend the standard Forms button in Java and then use this class name in the implementation class property then the Java for your button will be used instead of the standard Forms button. And since it has extended the basic Forms button it has all the standard button functionality.
    There is a white paper on OTN about this and we have created a new white paper which will be out in a couple of months (I think).
    Regards
    Grant Ronald<HR></BLOCKQUOTE>
    null

  • How can i set class path in ubuntu JAVA_HOME ?

    how can i set class path in ubuntu <JAVA_HOME>?

    Note that on *nix
    environment variable names are case sensitive.
    Also, you are again being vague; is it [this it|http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/javac.html] or [that it|http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/java.html]

  • How to implement a singleton class across apps in a managed server}

    Hi ,
    I tried implementing a singleton class , and then invoking the same in a filter class.
    Both are then deployed as a web app (war file) in a managed server.
    I created a similar app , deployed the same as another app in the same managed server .
    I have a logger running which logs the singleton instances as well.
    But am getting two instances of the singleton class in the two apps - not the same .
    I was under the impression that , a singleton is loaded in the class loader level , and since all apps under the same managed server used the same JVM , singleton will only get initialized once.
    Am i missing something here ? or did i implement it wrong..?
    public class Test
       private static Test ref ;
       private DataSource X; 
       static int Y;
       long Z ;  
       private Test ()
          // Singleton
           Z= 100 ;
       public static synchronized Test getinstance()  throws NamingException, SQLException
          if(ref == null)
             ref = new Test() ;        
             InitialContext ic = new InitialContext();
             ref.X = (DataSource)ic.lookup ("jdbc/Views");
          return ref ;       
       public Object clone()throws CloneNotSupportedException
           throw new CloneNotSupportedException();
       public int sampleMethod (int X) throws SQLException
    public final class Filter implements Filter
         public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException
              try
                   Test ref = Test.getinstance();
                   log.logNow(ref.toString());
    }Edited by: Tom on Dec 8, 2010 2:45 PM
    Edited by: Tom on Dec 8, 2010 2:46 PM

    Tom wrote:
    Hi ,
    I tried implementing a singleton class , and then invoking the same in a filter class.
    Both are then deployed as a web app (war file) in a managed server.
    I created a similar app , deployed the same as another app in the same managed server .
    I have a logger running which logs the singleton instances as well.
    But am getting two instances of the singleton class in the two apps - not the same .Two apps = two instances.
    Basically by definition.
    >
    I was under the impression that , a singleton is loaded in the class loader level , and since all apps under the same managed server used the same JVM , singleton will only get initialized once. A class is loaded by a class loader.
    Any class loader that loads a class, by definition loads the class.
    A VM can have many class loaders. And far as I know every JEE server in existance that anyone uses, uses class loaders.
    And finally there might be a problem with the architecture/design of a JEE system which has two applications but which is trying to solve it with a singleton. That suggests a there might be concept problem with understanding what an "app" is in the first place.

  • Can't set class cfol error

    hey
        i could really use some help here. Basically I am trying to get a sript working that monitors where an application is open and if it isn't then for it to copy a folder (that countains many files and subfolders) over to a hidden mounted volume...here is what I have:
    -- insert your existing code here  on idle tell application "System Events" to ¬ set exists_ to exists process "name of app to watch"  if exists_ is false then tell application "Finder" duplicate folder "path:to:source:" to folder "path:to:destination:" end tell return -- quit script end if  return 10 -- checks every 10 seconds to see if app has been quit end idle
    any ideas? it gives me the following error:
    "can't set <<class cfol>> "/Volumes/VantageGaming/Batman Arkham Aslyum/SaveData/6a38a6200000001 of appliation "Finder" to <<class cfol>> "Users?VantageGaming/Library/Application Support/Feral Interactive/Batman Arkham Aslyum/SaveData/6a38a6200000001" of application "Finder".
    i would realy appreciate any help...i'm would consider myself a novice!
    peace will

    hey
         EDIT: sorry here is the code that i have tried....we are gettting close but applescript for me is so frustrating! thanks for taking the time to play with the code...
    i'm using this code:
    on idle
              set source to "/Users/VantageGaming/Library/Application Support/Feral Interactive/Batman Arkham
    Asylum/SaveData/6a38a62600000001" as POSIX file
              set destination to "/Volumes/VantageGaming/Batman Arkham Asylum/SaveData/6a38a62600000001" as POSIX file
              tell application "System Events" to ¬
                        set exists_ to exists process "Batman Arkham Asylum"
              if exists_ is false then
                        tell application "Finder" to duplicate "/Users/VantageGaming/Library/Application Support/Feral Interactive/Batman Arkham Asylum/SaveData/6a38a62600000001" to "/Volumes/VantageGaming/Batman Arkham Asylum/SaveData/6a38a62600000001"
                        return
              end if
              return 10
    end idle
    it is still returning me a Can't make "/Users/VantageGaming/Library/Application Support/Feral Interactive/Batman Arkham Asylum/SaveData/6a38a62600000001" into type item
    i'm trying to research about type item failures but can't find anything relevant yet....
    uhhh
    peace will
    peace will

  • How to implement a java class

    dear friends
    i use forms6i server and oracle 9i server edition,under windows 2000 server
    i try to implement a java class for a bean area. i do the following :
    from the property palette i write the class name in implementaion class property . the class name is 'arc.class' and it is located in <oracle_home>/forms60/java
    but the fellowing error appears
    frm-13008 cannot find javabean with name 'arc.class'
    would any one help please

    Dear Grant Ronald
    thank you very much for helping me . now i undersatand how to implement a class. but i have another question ,and i wish you ccould help me .
    i try to import a java class, i do the following:
    From the program menue i choose Import Java Class
    but the following error appears
    (pde-uji001 faild to create JVM)
    by the way i use forms6i server and oracle 9i server under windows 2000 server
    thanks in advance
    tarek

  • Custom Reporting on Imported Hardware Inventory set classes for USB Super Speed driver

    I am trying to create a report with report builder 3.0 to pull data on a USB Super Speed driver under
    ClassContext("local|HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Class{36fc9e60-c465-11cf-8056-444553540000}")
    I tried following the article
    http://blogs.technet.com/b/configmgr_geek_speak/archive/2013/11/10/inventorying-and-reporting-network-adapter-driver-details-and-how-to-report-only-the-wireless-type-in-configuration-manager-2012.aspx and changed a few of the Class descriptions and cannot
    get any data in the report. 
    I imported this into the Hardware Inventory set classes:
    #pragma namespace ("\\\\.\\root\\cimv2\\sms")
    [ SMS_Report (TRUE),
    SMS_Group_Name ("USB"),
    SMS_Class_ID ("MICROSOFT|USB|1.0"),
    Namespace ("\\\\\\\\localhost\\\\root\\\\cimv2") ]
    class Win32Reg_USB : SMS_Class_Template
    [SMS_Report (TRUE), key ]
    string Index;
    [SMS_Report (TRUE) ]
    string DriverDesc;
    [SMS_Report (TRUE) ]
    string DriverVersion;
    [SMS_Report (TRUE) ]
    string DriverDate;
    [SMS_Report (TRUE) ]
    string ProviderName;
    Under the Configuration.mof file I am not sure what to change in order to report on this.  Any help appreciated.  We are looking for all of the USB super speed driver details.
    Thanks,
    Brit

    have you looked at V_GS_system_Device if your device info available or not ? Use the below SQL query to list all system devices on your clients. 
    SELECT DISTINCT name0 FROM v_GS_SYSTEM_DEVICES 
    GROUP BY name0
    Eswar Koneti | Configmgr Blog: www.eskonr.com | Linkedin: Eswar Koneti
    | Twitter: eskonr

  • Is there any way an iPhone app developer can implement low power class 3 Bluetooth?

    Is there any way an iPhone app developer can implement low power class 3 Bluetooth?

    Ah-HA!  I knew there had to be a way!
    Not quite the same in 10.6, but close enough to find it:
    It's iTunes>apps, not iTunes>iPhone>apps.  I didn't realize there were different windows.
    Not double-click, but control-click.  Close enough.
    Easy-Peasy, now that you showed me how.
    Thanks, Barry.
    --Gil

  • [svn] 4130: Remove @private from IXMLNotifiable. as since it is implemented by another class and should appear in ASDoc

    Revision: 4130
    Author: [email protected]
    Date: 2008-11-18 07:36:15 -0800 (Tue, 18 Nov 2008)
    Log Message:
    Remove @private from IXMLNotifiable.as since it is implemented by another class and should appear in ASDoc
    QE Notes: None
    Doc Notes: None
    Bugs: -
    Modified Paths:
    flex/sdk/trunk/frameworks/projects/framework/src/mx/utils/IXMLNotifiable.as

    My output is listed below. Can I solve the issue by replacing the following line in /etc/postfix/main.cf?
    mydestination = $myhostname,localhost.$mydomain,localhost
    with
    mydestination = $mydomain,localhost.$mydomain,localhost
    command_directory = /usr/sbin
    config_directory = /etc/postfix
    content_filter = smtp-amavis:[127.0.0.1]:10024
    daemon_directory = /usr/libexec/postfix
    debugpeerlevel = 2
    enableserveroptions = yes
    html_directory = no
    inet_interfaces = all
    mail_owner = _postfix
    mailboxsizelimit = 0
    mailbox_transport = cyrus
    mailq_path = /usr/bin/mailq
    manpage_directory = /usr/share/man
    messagesizelimit = 10485760
    mydestination = $myhostname,localhost.$mydomain,localhost
    mydomain = domain.com
    mydomain_fallback = localhost
    myhostname = pinky.domain.com
    newaliases_path = /usr/bin/newaliases
    queue_directory = /private/var/spool/postfix
    readme_directory = /usr/share/doc/postfix
    relayhost =
    sample_directory = /usr/share/doc/postfix/examples
    sendmail_path = /usr/sbin/sendmail
    setgid_group = _postdrop
    smtpdpw_server_securityoptions = gssapi
    smtpdrecipientrestrictions = permitsasl_authenticated,permit_mynetworks,reject_unauthdestination,permit
    smtpdsasl_authenable = yes
    smtpduse_pwserver = yes
    unknownlocal_recipient_rejectcode = 550
    virtualmailboxdomains = hash:/etc/postfix/virtual_domains
    virtual_transport = lmtp:unix:/var/imap/socket/lmtp

  • How to set class path for mysql

    hai, I have been trying to make a java program read from mysql database. but i don't know how to set the class path for mysql-connector-java-5_1_.0.6-bin. i set the class path in system variable as C:\Program Files\Java\jdk1.5.0_08\jre\lib\ext\mysql-connector-java-5_1_.0.6-bin.
    in the command prompt, i compile C:\javac abc.java and run java abc.
    when run it come out error java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    i am using Window xp. can anybody help me??? TQ.

    hai, I have been trying to make a java program read
    from mysql database. but i don't know how to set the
    class path for mysql-connector-java-5_1_.0.6-bin. i
    set the class path in system variable as C:\Program
    Files\Java\jdk1.5.0_08\jre\lib\ext\mysql-connector-jav
    a-5_1_.0.6-bin.
    in the command prompt, i compile C:\javac abc.java
    and run java abc.
    when run it come out error
    java.lang.ClassNotFoundException:
    com.mysql.jdbc.Driver
    i am using Window xp. can anybody help me??? TQ.Right click on my computer icon,
    Goto properties->advanced->environment variables.
    Look for 'classpath' under system variable.
    Select it and click edit.
    put ';' and path of the mysql connector jar at the end
    suppose if u have jar file under d:/driver/mysqlconnector.jar
    thn put this value in variable value text box
    ;d:/driver/mysqlconnector.jar
    or simply put ur driver jar file in jre/lib/ext folder
    D:\j2sdk1.4.2_03\jre\lib\ext
    [Servlet tutorial|http://www.jsptube.com]

Maybe you are looking for