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

Similar Messages

  • 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.

  • (Class ? extends Set String ) Class.forName("example.SetImpl").asSubclass

    Is there a way to do the following without an Unchecked cast?
    Class<? extends Set<String>> clazz;
    clazz = (Class<? extends Set<String>>) Class.forName("example.SetImpl").asSubclass(Set.class);
    Set<String> mySet = clazz.newInstance();
    cheers,
    reto

    No. The last line will always generate that warning making the second line pointless. There is no way to create a new instance of a generic class because there is (for most intents and purposes) no such thing as a generic class at runtime.

  • 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

  • CS3 Extended Setting Actions/Droplets to print

    Look in ways to resize image/files to what format; then set droplets to print images/files 4 x 6 photos. I can set actions to 4 x 6 however, can't figure out to get them to print automatically upon dropping files into droplet to print. NEED HELP SOON!!
    Kevin

    Photoshop CS3 Extended is not intended for still Photography. It would be better used in motion Photography (the Movie Industry). PSCS3 Extended can be used for creative work to compliment Adobe After Effects which does for motion Photography what Photoshop does for still Photography.

  • RE4000W extender set up on other devices

    I have just set up my Linksys RE4000W extender on my Surface Pro 3 tablet. I have a windows 8,1 smart phone and my wife has an iPad. Do I have to set up a driver on each of those additional devices to benefit from the extender? If so, do I simply install a driver on each?
    Solved!
    Go to Solution.

    You need to place your extender in an area where there is still a good connection from the router. Just use a handheld device (phone or tablet) to check for your router's signal strength. Once you can find a place where there is still 2-3 bars signal, then that's the perfect location for your extender. Changing the wireless channel on your router will also help to avoid interference in your network; best channels are 1, 6, and 11.

  • How to change charset into extended set?

    Hi, my server is setup with en_US.iso8859-1, I would necessity to change this set to get a special accented chars, such as "�,�,�,�" and so on. In practice, I would change this charset to it_IT.iso8859-15.
    I tried to change var locale, such as LC_* but it doesn't work, I still have old character set. How to do this?
    Thanks

    Hi,
    If you are attempting this on Solaris 8, then would suggest to have look on info doc 23063 on http://sunsolve.sun.com.
    Hope this helps you.
    Thanks,
    Santosh

  • Implementing Extended WM

    Dear Experts,
    I used to implement Material management then Implement WM which is a component in the ERP , But now there is a client wants to implement EWM , What I know that there are only two choices :
    1. Install ECC - ERP and install the EWM Addon
    2. Install SCM EWM 7.0
    - So is this mean that I should first implement MM them Implement EWM ? , with another way " Could I Implement EWM without Inventory Transactions in Inventory Management Module  " ?
    - Please provide me with documents and links to guide me how to implement EWM only with out MM transactions , and If it not possible could I only use " Non SAP ERP System " to be alternative of MM Module ?
    Thanks in Advanced
    Best Regards

    Dear SAP SAP,
    In both scenario's you describe EWM has been design to integrate to one or more ERP systems as a decentralised system even as an add on.
    EWM does not explisitally need SAP MM to operate but the ERP system/s SAP or other will require material management functionallity to be present.
    The MM module will be required in the ERP system (in both scenario's) to allow the creation of deliveries and the management of inventory (quantity& value) and associated funtions such as ATP checks.  If a non SAP ERP is being integrate with then the equivalent MM functionallity will be required to enable the ERP to take orders , "manage ineventory" and invoice.
    Thanks James

  • Implementing Set using BST

    Hi, I am implementing the Set using Binary Search tree but am stuck and I cannot go further. Could someone help me get this code working? I am trying to make the add method to work but it does not compile and it says it cannot find the compareTo(java.lang.Object) method. When i don't have the compareTo method, it says i have to override the compareTo. I think i can get the contains method working if the add method works. Code below:
    import java.util.*;
    import java.lang.*;
    public class SetImplementation<E> implements SimpleSet <E> {
        private TreeNode root ;
        private int NodeCount ;
      public SetImplementation() {
          root = null ;
          NodeCount = 0 ;
      public boolean add(Object obj) {
         if(root == null) {
            root = new TreeNode(obj) ;
            NodeCount++ ;
            return true ;
       return recursiveAdd(root, obj) ;
    public boolean recursiveAdd(TreeNode node, Object obj) {
         int compareResult = (node.getObj().compareTo(obj)) ;
             if(compareResult == 0) {
                System.out.println("You cannot duplicate values") ;
                return false;
             else if(compareResult < 0) {
                node.left = add( node.left, obj );
                NodeCount++ ;
                return true ;
             else if(compareResult > 0) {
                node.left = add( node.right, obj );
                NodeCount++ ;
                return true ;
      public boolean contains(Object o) { return false ;  }
      public boolean isEmpty() { return root == null ; }
      public int size() { return NodeCount ; }
      public void clear() { root = null ;  }
      public class TreeNode implements Comparable {
          Object obj ;
          TreeNode left , right ;
          public TreeNode(Object o) {
              obj = o ;
              left = null ;
              right = null ;
          public int compareTo(Object other) {
             return 1; //I don't know how to do the comparison. I hav never used this interface
          }             //I never used the comparable interface before, so i am just out of ideas
        }               //So i just try to return an integer to se if it works. BUt it does not.
     

    You're comparing the Object references from your TreeNode classes but these are not Comparable. So, you should store Comparables in your TreeNode's. And you also want to add types to your tree that are Comparable, right?
    If I were you, I'd first try to get this working without the generics (the strange brackets: <E>). When that works, extend your code using generics. Here's a small start:
    class SetImplementation implements SimpleSet {
        public boolean add(Comparable obj) { // <-- Comparable here!
            return recursiveAdd(root, obj) ;
        private boolean recursiveAdd(TreeNode node, Comparable obj) { // <-- Comparable here! (and made it 'private')
            int compareResult = node.obj.compareTo(obj) ;
        public class TreeNode {
            Comparable obj ; // <-- Comparable here!
    }

  • Update set of books in implementation options ??

    we are doing project setup[ in one of the test instance , How ever while doing thta in implementation options set of books is saved incorrectly and now it is freezed (not able to change the set of books field) ..Navigation setup -->system-->implementation options-->Systme Tab
    can we update this set of books from back end ..and if we do where all can we get an impact ..!!
    any suggestions ..

    Though the form field only updates the SOB in the pa_implementations_all table. It is not advised to do backend updates. I would advise to log a SR and propose your strategy which the Oracle Dev team will analyze and may approve it.
    Hope this helps !
    ~Sathish Raju
    www.projectsaccounting.com

  • Implementing Set Interface

    i have to implement the set interface without using any features, other thaset itself, from java.util. i have to create my own data structure(s) to implement it. any suggestions on which way to go.
    thanks in advance.

    Hi,
    Use java.util.Vector class as your data structure. A set is just a list that doesn't allow duplicates. You can use the Vector method: contains to figure out if it already exists or not.
    import java.util.*;
    public class MySet
      Vector data = new Vector();
      public Object get( int i )
        if( i >= 0 && i < data.size() )
          return( data.elementAt( i ) );
        return( null );
      public boolean add( Object ob )
        if( !data.contains( ob ) )
          data.add( ob );
          return( true );
        return( false );
    }Regards,
    Manfred.

  • Why Extended Encoding Sets are not available?

    I m using JDK1.4. Why I got the UnsupportedCharsetException from this line:
    CharsetDecoder cd = Charset.forName("Big5").newDecoder();
    When I print out the available charsets in the system, I realised that "Big5" and all extended sets are not included (http://java.sun.com/j2se/1.3/docs/guide/intl/encoding.doc.html). Anybody can explain and help me to get these extended sets?
    Following is the output from my code >>>
    available charsets:
    ISO-8859-1
    ISO_8859-1:1987
    ISO8859_1
    8859_1
    iso-ir-100
    cp819
    ISO_8859_1
    ISO8859-1
    latin1
    IBM819
    IBM-819
    l1
    ISO_8859-1
    csISOLatin1
    819
    ISO-8859-15
    8859_15
    923
    LATIN9
    ISO_8859-15
    ISO8859_15_FDIS
    cp923
    L9
    LATIN0
    csISOlatin9
    ISO8859-15
    IBM923
    ISO-8859-15
    IBM-923
    csISOlatin0
    US-ASCII
    us
    ISO_646.irv:1991
    ANSI_X3.4-1968
    iso-ir-6
    646
    ISO646-US
    cp367
    ANSI_X3.4-1986
    csASCII
    ASCII
    iso_646.irv:1983
    IBM367
    UTF-16
    UTF_16
    UTF-16BE
    X-UTF-16BE
    ISO-10646-UCS-2
    UTF_16BE
    UTF-16LE
    UTF_16LE
    X-UTF-16LE
    UTF-8
    UTF8
    windows-1252
    cp1252
    java.nio.charset.UnsupportedCharsetException: Big5
         at java.nio.charset.Charset.forName(Charset.java:428)
         at com.bluewave.levisapd.TestBean.uniDecode(TestBean.java:139)
         at com.bluewave.levisapd.Test.main(Test.java:18)
    Exception in thread "main"

    Hi, there should be a file charsets.jar in your \jre\lib folder. It contains the optional encodings, as described in http://java.sun.com/j2se/1.4/docs/guide/intl/encoding.doc.html
    Make sure it's in your classpath.
    Cheers, HJK

  • Why extended Classic is implemented

    Hi Everybody,
    I was working in SAP SRM for past 3 years and only Support Experience. Yesterday attended an interview and he asked me why your client has implemented Extended Classic why not Classic Scenario?
    I know it depends to client-to-client.
    Can any one let me know the list of points need to be discussed to support this question. My answer was not impressive.
    Sree

    Hi Sree,
    You are right here it depends on the client whether to configure the system for extended classic and classic scenario.
    The extended classic scenario suits customer who wants to
    their purchasing department to save time and money by using the streamlined purchasing functionality of SAP SRM
    use the full sourcing capabilities offered by SAP SRM, yet who also want to be able to confirm and invoice direct materials
    the flexibility of being able to pre-enter confirmations and invoices
    Where the classic scenario suits the customer who wants:
    wide user group, for example employees not necessarily working in the purchasing department, to be able to enter their requirements quickly and easily. SAP SRM’s functionality and ease of navigation allow this, as it requires only minimal training
    their purchasing department to operate solely with the functionality offered by the backend system(s)
    For whom a transfer of purchasing activities to SAP SRM is not viable in SAP SRM
    You can use both the classic and extended classic capabilities by configuring the product categories
    Please let me know if the above answer is helpful.
    Best Regards,
    Ankit Jain

  • Implement Set Interface

    I have been give the task of "implementing the Set interface" in Java for a project. I believe what needs to be done is overwriting the methods I need from the Set interface, but I'm not exactly sure if this is correct, or how I would start to do this. Could anyone point me in the right direction? TIA
    Edited by: prem1era on Jul 8, 2009 7:19 AM
    Edited by: prem1era on Jul 8, 2009 7:25 AM

    Ok, now that I understand more what I am doing, I have another question and maybe I should post a new topic for it, but I'll see if I can get any responses here first. Now that I am implementing Set correctly my goal is to use Set to store an object in a file instead of in memory. So this is what I have so far. For the add method, I am planning on using the object as an argument. I want to check to make sure that the object being added is not already included in that file. So within the add method I am going to read through the file, look for that object and if it is not present I am going to add it. Else, I will be returning false. Does this sound correct?
    import java.io.FileWriter;
    import java.io.PrintWriter;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.Set;
    public class RegistrySet implements Set {
         private String registryFile;
         private PrintWriter pw;
         public RegistrySet(String registryFile){
              this.registryFile = registryFile;
         public boolean add(Object o) {
              return false;
         }

  • Implementing Set

    I have been working on implementing the Set interface, in particular my question is about the Add method. I have an internal Set within my implemented Set that keeps a copy of implemented Set. What I'm not sure about is if I am implementing it correctly. The boolean return value in the Add method is confusing me I think. Here is my code for the implemented class can you let me know if this is correct?
         public RegistrySet(String registryFile){
              this.registryFile = registryFile;
         public void init() throws IOException {
              this.br = new BufferedReader(new FileReader(this.registryFile));
              this.pw = new PrintWriter(new FileWriter(this.registryFile, true));
              String itemId = null;
              while ( (itemId = br.readLine()) != null ){
                   internalSet.add(itemId);     
         public boolean add(Object o) {
              internalSet.add(o);
              Iterator it = internalSet.iterator();
              while ( it.hasNext() ){
                   String itemId = (String)it.next();
                   this.pw.println(itemId);
              return false;
         }Edited by: prem1era on Jul 9, 2009 7:57 AM

    prem1era wrote:
    Ok, then that is my question. How do I return what internalSet.add() returned?You're joking, right? Seriously, sit down and think for a minute. If you don't know how to do that, then you need to go back to the very beginning and not worry about trying to implement your own set right now.

Maybe you are looking for