Nested object equality - design pattern

Looking to solve a problem in my own code, I wanted to see if and how the problem is solved in the java library.
I would have liked this code to output "true", to see how it's done.
Set set1 = new HashSet();
set1.add("a value");
set1.add(set1);
Set set2 = new HashSet();
set2.add("a value");
set2.add(set2);
System.out.println(set1.equals(set2));Well the code ends with a StackOverflowError on hashCode(). Just using a Set which implements hashCode to return a constant value would shift the problem to the equals-method.
I think one possible solution would be to implement the hashCode method to set a instance variable (computingHash = true) while hashcodes of fields are computed. If the variable is set when hashcode is invoke a RecursiveHashRuntimeException is thrown which is is caught by the invoking hashcode method which would then return a constant value or ignore the corresponding field for hash-computation.
Similarly the equals method would add the obj (passed to equals) to a set (instance variable) named assumeEqualTo, if the obj is in assumeEqualTo when the method is invoked it returns true. The value is removed from assumeEqualTo before the method that added it returns.
This approach would require the equals and hashcode methods to be - at least partially - synchronized (if multithreading is an issue), an alternative would be to use ThreadLocal variables to detect and handle recursive invocations.
I'm not sure how the two approaches compare in terms of performance, and I would welcome any other approach to solve the problem. Note that the class being compared should not be required to know details about the contained classes and the nesting may also be indirect as in:
Set set1 = new HashSet();
Set set2 = new HashSet();
set1.add("a value");
set1.add(set2);
set2.add("a value");
set2.add(set1);
System.out.println(set1.equals(set2));Also it would be nice if the impact on performance could be kept minimal for all instance that happens not to be self-containg.
cheers,
reto

should be slightly different as for sets the orderis
irrelevant
I don't follow. You would presumably only return
true as a whole if every element in the Set also
returned true. So, yes, order is irrelevant. just wanted to say that you must return true iff you find a mapping from set1 to set2 where all elements are equals
No, I mean that if you add a Set to itself, and then
iterate over it, you will implicitly be performing
recursion, leading to a StackOverflowError
eventually. That is why you need to store a
collection (or array) with all the objects already
analyzed. What do you mean by "already analyzed"? I mean how would you prevent recursion with this?
You need to compare what is being
currently being inspected along with checking what
you already processed for object equality (==) so you
do not get the stack overflow.I don't get it, in
Set set1 = new HashSet();
Set set2 = new HashSet();
set1.add(set2);
set2.add(set1);
set1.equals(set2);The equals method returns true iff set2.equals(set1), which would - in the algorithm I proposed - return set1.add(set2) which is true as set2 is contained in the Set assumeEqualTo. I interpreted the contract specified by java.util.Set to return true on equals for indistinguishable object - not sure if this is correct for mutually referencing sets, but pretty convinced for non-refrencing self containing sets, as in my first example or for all sets returned by:
createSet() {
  Set s1 = new HashSet();
  Set s2 = new HashSet();
  s2.add(s1);
  s1.add(s2);
}Imho, it would break be against the specification in java.util.Set to return false on createSet().equals(createSet()).
reto

Similar Messages

  • ABAP Object X Design Patterns X Extreme Program

    Hi Evebody,
    I’m postgraduate in Object Oriented Analysis and Programming.
    I’ve been working with ABAP procedural development for two years and I’ve started to work with ABAP Objects has few months.
    I’d like to get deeply knowledge in my development’s skills, could someone tell me if <b>ABAP Object X Designer Patterns X Extreme Program</b> is a good path to follow?
    I’d like to share material and guides about this topic.
    I’ve already bought these books to help me.
    <b>ABAP Objects</b> - H. Keller; Hardcover <i>(Pre-Order)</i>
    <b>Design Patterns Explained</b> - Alan Shalloway
    I’ll be very grateful with any help.

    > And do you think these themes are a great combination
    > for ABAP development?
    Design pattern are very abstract and can be used with any OO programming language. The implementations will differ but the core concepts are always the same.
    XP is an agile development process and can also be used with any programming language.
    Learning what design pattern are and how to use them is very important in my opinion. Most companies expect that you are familiar and have experience with them.
    Extreme Programming (XP) on the other side is different. When I began to explore XP it got me started on how software should be developed in general. Since the concepts behind XP are quite different, it should at least stimulate you to start thinking about how you develop software at the moment and if there might be better ways of doing it.
    If you have only time to study one subject go for the design pattern. You might also consider reading the following books if you want to improve your OO coding skills:
    <a href="http://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672/ref=pd_bbs_sr_1/102-4989641-7820932?ie=UTF8&s=books&qid=1173448197&sr=8-1">Refactoring: Improving the Design of Existing Code (a true classic)</a>
    <a href="http://www.amazon.com/Refactoring-Patterns-Addison-Wesley-Signature-Kerievsky/dp/0321213351/ref=pd_bbs_sr_2/102-4989641-7820932?ie=UTF8&s=books&qid=1173448197&sr=8-2">Refactoring to Patterns (Shows how to improve code by introducing design pattern)</a>
    cheers
    Thomas

  • ANN: New Design Pattern (DAO)

    Hello,
    Thanks for your overwhelming response to our previous sample applications demonstrating various [url http://www.oracle.com/technology/sample_code/tech/java/j2ee/designpattern/index.html]design patterns.
    Continuing with the series, this month we have showcased the [url http://www.oracle.com/technology/sample_code/tech/java/j2ee/designpattern/dataaccesstier/index.html]Data Access Object (DAO) Design Pattern which is considered as a best practice for applications accessesing the database or the underlying persistence layer from the business tier.
    The DAO implements the access mechanism required to work with the data source. The data source could be a persistent store like an RDBMS, an external service like a B2B exchange, a repository like an LDAP database, or an XML Repository. Using the scenario of web based News Application, this sample application demonstrates the effective use of this pattern.
    [url http://www.oracle.com/technology/sample_code/tech/java/j2ee/designpattern/dataaccesstier/index.html]Download the sample application to learn more about this pattern.
    More Sample Applications are available at [url http://www.oracle.com/technology/sample_code/index.html]
    http://www.oracle.com/technology/sample_code/index.html
    Thanks,
    Rajat
    OTN Team

    Hi
    This is because you are not using the latest jdbc driver version. Either use the latest ojdbc14.jar downloadable from the location given in the readme(Oracle Database 10g (10.1.0.2.0) drivers),
    Or simply comment this part in the code.
    Also you may just replace the close method call with ods=null;
    Hope this helps
    Shrinivas

  • Design patterns in log4j

    hi
    i have a question that was asked to me
    what pattern does log4j appender(consoleappender,rollingfileappender etc) implement?
    candidates can be dao, facade etc....
    can somebody xplain what pattern does it use and how
    techy

    actually this question was given in an exam and the
    answer that the teacher gave was proxy pattern.Actually, if you think about it, only the individuals that programmed the log4j code know what design patterns they actually used.
    As an outsider, just because an application "looks" like a pattern might have been used, does not mean it was actually used to design the application.
    Futhermore, just because an application's functionality may fit in well with how one envisions the pattern's possible implementation, this too, does automatically equate or represent the fact that the pattern(s) were used.
    This is a poor question to have on an exam, especailly if the individuals taking the exam were not the ones that worked on log4j. If the exam was given to log4j programmers, then it is a reasonable question.
    To ask this question to assess knowledge/experience with log4j or object-oriented design patterns is a bad decision, in my opinion.
    Only close and detailed inspection of the log4j source code will reveal what design patterns were actually used. Again, to question someone on this is inappropriate, unless it is for the log4j development team, in my opinion.
    i m not able to understand how it applies proxy
    pattern?I understand your confusion.

  • Design Patterns

    Hi,
    I am new to these forums.
    I know that there are 4 types of J2EE Design Patterns.
    1. Fundamental
    2. Structural
    3. Creational
    4. Behavioral.
    Hope that's correct. Can anyone plz tell me what's the difference between them?
    Also, examples for them. ie; Under which category mentioned above, patterns like Singleton,ServiceLocator,Session facade, DAO,DTO etc fall?
    Thanks in advance.

    BigDaddyLoveHandles wrote:
    Kumaari wrote:
    Please give me some explanation in your words.
    Thanks in advance.In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations. Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved. Algorithms are not thought of as design patterns, since they solve computational problems rather than design problems.
    Not all software patterns are design patterns. Design patterns deal specifically with problems at the level of software design. Other kinds of patterns, such as architectural patterns, describe problems and solutions that have alternative scopes.
    Better?
    Brilliant. Bravo sir, bravo

  • What is a design pattern?

    Howdy,
    I hear a lot of talk of deasign patterns in ABAP...
    My question is what on earth is a design pattern and why/how would it be useful?
    Any ideas anyone

    Hi Steve.
    The good point to start with design patterns is to read book "Design Patterns - Elements of Reusable Object-Oriented Software" by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides. It gives strong, consistent understanding of patterns basis with real life examples.
    Short introduction extract:
    "Christopher Alexander says, "Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice". Even though Alexander was talking about patterns in buildings and towns, what he says is true about object-oriented design patterns. Our solutions are expressed in terms of objects and interfaces instead of walls and doors, but at the core of both kinds of patterns is a solution to a problem in a context.
    In general, a pattern has four essential elements:
    The pattern name is a handle we can use to describe a design problem, its solutions, and consequences in a word or two. Naming a pattern immediately increases our design vocabulary. It lets us design at a higher level of abstraction. Having a vocabulary for patterns lets us talk about them with our colleagues, in our documentation, and even to ourselves. It makes it easier to think about designs and to communicate them and their trade-offs to others. Finding good names has been one of the hardest parts of developing our catalog.
    The problem describes when to apply the pattern. It explains the problem and its context. It might describe specific design problems such as how to represent algorithms as objects. It might describe class or object structures that are symptomatic of an inflexible design. Sometimes the problem will include a list of conditions that must be met before it makes sense to apply the pattern.
    The solution describes the elements that make up the design, their relationships, responsibilities, and collaborations. The solution doesn't describe a particular concrete design or implementation, because a pattern is like a template that can be applied in many different situations. Instead, the pattern provides an abstract description of a design problem and how a general arrangement of elements (classes and objects in our case) solves it.
    The consequences are the results and trade-offs of applying the pattern. Though consequences are often unvoiced when we describe design decisions, they are critical for evaluating design alternatives and for understanding the costs and benefits of applying the pattern. The consequences for software often concern space and time trade-offs. They may address language and implementation issues as well. Since reuse is often a factor in object-oriented design, the consequences of a pattern include its impact on a system's flexibility, extensibility, or portability. Listing these consequences explicitly helps you understand and evaluate them."
    Regards,
    Maxim.

  • Design Pattern Names

    Started fooling around with some industry-specific software implementations. In one software design document, I came across a reference to an old familiar term "design patterns". This part of the text was describing XML Schema Design Patterns. Below is the first paragraph, which made me laugh :o)
    "As with software design, there are design patterns associated with XML Schema design. The most popular XML Schema design patterns are Russian Doll, Salami, Bologna, Venetian Blind and Garden of Eden."
    Unlike the GoF, these guys seem to be hungry....
    Anybody have any experience implementing the Bologna design pattern?

    I agree with dubwai's take on this. These are not design patterns, in my opinion. These are language-specific, very defined, programming algorithms for handling a few typical issues with processsing XML-based data.
    To label these as "design patterns" is a bad thing and just another step to adding to the confusion of what an object-oriented design pattern really is.
    Moreover, the name of an object-oriented design has a very important role. Care should be taken when naming a design pattern; a name should convey the meaning or intent of the pattern. To call a "design pattern" Salami Slice is a joke, in my opinion.
    One of the most important aspects of design patterns is that they are NOT specific, coded solutions to any problem. And, they are design tools to guide the process of designing software. Implementation details are outside the scope of design patterns.
    Generally, I find that these work well with the Provolone and SandwichOil patterns. lol

  • Design pattern for several conditions

    Hi;
    I would like to implement an search algorithm which use many conditions (search criteria).
    For Example
    Begin :
    If criteria A && B are OK => if criteria C is OK => etc...
    Else criteria D && F are OK => if criteria C is OK => etc...
    Else etc...
    which design pattern or another design correspond to my requirement ?
    Regards;

    You are missing the point somewhere. Object-oriented design patterns are tools used to design object-oriented applications. There is a certain limit to size that is associated with warranted usage.
    In other words, the issue of your post is a trivial element of conditional processing. There is no such design pattern to apply to such a thing because that is not what design patterns are used for.
    Aside, some forum "genius" is going to post some application of a design pattern to this issue and then call me crazy. Looking forward to it :o)
    Your question would be better suited if it asked for what type of conditional processing algorithm might work well. In Java there are a few to work with. If statement, do while statement , while statement, case, etc.

  • Is MVC a architecture or Design Pattern?.

    Hi,
    It may be simple question,but i need clarification on this.
    Thanks in Advance.

    Model View Controller is an object-oriented design pattern.
    Some individuals may choose to use it (questionably) to describe a piece of a software architecture. In this case they are using the design pattern to describe only an element of an architecture.
    MVC outlines how objects will communicate in a three-tier system consisting of a business model and a presentation layer.
    MVC does not describe hardware configuration, load balancing, clustering, firewalls, routers, security constraints, resource pooling, and other critical details of a software architecture.
    A software architecture design may include and/or use the MVC design pattern to indicate how the technical design of the application should be designed. Here the decision to use MVC is part of the architectural design. It is one specification of the architecture design. There are many other elements of a software architecture design that have nothing to do with MVC.
    MVC by itself is a simple object-oriented design pattern. It cannot be used to describe and/or design a software architecture.

  • ABAP objects design patterns

    hi all,
        can any one send me the Design patterns used for ABAP objects programming in ABAP. eg mvc and sample code which uses the design patterns
    cheers
    senthil

    Of course that program is not an object design pattern
    (Its just a little ABAP Objects syntax demo that I wrote  years ago
    I don't know about a list of OO design patterns implemented in ABAP Objects.
    A very simple one, a Singleton might look like this:
    <b>* cl_singleton: Eager Variant
    CLASS cl_singleton DEFINITION FINAL
                                  CREATE PRIVATE.
      PUBLIC SECTION.
        CLASS-METHODS: class_constructor,
                       get_singleton RETURNING VALUE(singleton)
                                               TYPE REF TO cl_singleton.
      PRIVATE SECTION.
        CLASS-DATA singleton TYPE REF TO cl_singleton.
    ENDCLASS.
    CLASS cl_singleton IMPLEMENTATION.
      METHOD class_constructor.
        CREATE OBJECT singleton.
      ENDMETHOD.
      METHOD get_singleton.
        singleton = cl_singleton=>singleton.
      ENDMETHOD.
    ENDCLASS.
    cl_singleton: Lazy Variant
    CLASS cl_singleton DEFINITION FINAL
                                  CREATE PRIVATE.
      PUBLIC SECTION.
        CLASS-METHODS get_singleton RETURNING VALUE(singleton)
                                              TYPE REF TO cl_singleton.
      PRIVATE SECTION.
        CLASS-DATA singleton TYPE REF TO cl_singleton.
    ENDCLASS.
    CLASS cl_singleton IMPLEMENTATION.
      METHOD get_singleton.
        IF cl_singleton=>singleton IS INITIAL.
          CREATE OBJECT cl_singleton=>singleton.
        ENDIF.
        singleton = cl_singleton=>singleton.
      ENDMETHOD.
    ENDCLASS.</b>

  • Design Pattern and ABAP Objects

    Hello Friends,
    I would like to know, if ABAP Objects can be used to do pattern oriented programming ?
    For example GANG of four has provided almost more then 30 design pattern ( MVC, singelton, Obserable, FACADE,,,etc) can we implement patterns using ABAP ??
    Many thanks
    Haider Syed

    Hi,
    Take a look at the following site:
    http://patternshare.org/
    It has all the basic patterns from the GOF and a lot more. I can recommend the ones from Martin Fowler but be sure you start with the ones from the GOF.
    All patterns are described by using UML so it's very easy to translate them into ABAP OO code.
    Regarding your other question. For the observer pattern I used an interface which the SAP had already created if_cm_observer and created my own abstract observable class. The observable class is nearly a 100% copy of the java.util. one
    regards
    Thomas

  • [disc]Design pattern - immutable objects.

    I`m working more often with immutable object because it doesn`t cost as much work to keep object consistent. But sometimes an object has to be build or a reference to his child objects has to be set.
    eg
    class A{
        private ArrayList bList = new ArrayList();  
        public A(){}
        public void addB(B b){
            bList.add(b);
    class B{
        private A a;
        public B(A a){
             this.a = a;
    }It`s now more complicated to make a immutable version of A.
    My question is how this problem could be solved. One solution is to add an immutable flag that could be set to true if the last B is added. But this couldn`t be checked compile time.
    Maybe there is a design pattern for this problem.
    I would like to discuss about this problem, so every thought is welcome.

    I have an Immutable Collection wrapper class that I use when I want to have a Collection be read-only.
    If you look at the JavaDoc for AbstractCollection you'll see that the add and remove methods throw UnsuportedOperationException.
    So all you have to do is implement the iterator() and size() methods. i.e.
    public class ImmutableCollection extends AbstractCollection {     
         private Collection collection;
          * only constructor
         public ImmutableCollection(Collection collection) {
              this.collection = collection;
          * returns the size of the collection
         public int size() {
              return collection.size();
          * returns a non-modifiable iterator over the elements of the collection
         public Iterator iterator() {
              return new Iterator() {
                   Iterator iterator = collection.iterator();
                   public boolean hasNext() {
                        return iterator.hasNext();
                   public Object next() {
                        return iterator.next();
                   public void remove() {
                        throw new UnsupportedOperationException();
    }

  • Data Transfer Objects Design Pattern

    Hi All,
    Could anyone tell me more about this DTO design pattern, as such when one should prefer it.
    Second is this pattern transaction safe or one would have to implement the same manually. Any updates would prove benefecial to me.

    Hi
    I do not understand what you mean.
    A dto is just an object which you populate in one layer and use in another layer.
    you do not need any jndi look for DTO , instead you lookup for ejbs , datasources ,....
    for example you lookup for some CMP , search and find some CMPs , populate DTO with those CMP and send the DTO to front layer.
    if it is not the answer , can you explain more about your requirements(S)

  • DAO object Design Pattern

    i have to develop a web base applecation which is database indepandent, to achive this functionlity i have to use DAO design pattern.
    can some one explane me more about this............................

    Data Access Object:
    Java BluePrints - Data Access Object
    JavaWorld: Write once, persist anywhere

  • Flex design pattern for BlazeDS transfer objects

    Dear Community,
    I have a question regarding the nature of objects transferd from BlazeDS backend to the Flex client.
    According to some adobe docs all the presentation logic should be in flex and BlazeDS should provide only services.
    The question is what kind of transfer objects should be used? with what level of abstraction?
    To make it more clear let's talk about a simple forum application like adobe forums.
    I have created a Forum service, which returns a Forum transfer object, which has a List of Threads, with each thread having a List of Messages.
    Flex gets the Forum transfer object and does all the presentaiton work.
    This is a very nice seperatin of concerns architecture BUT there are two major performance issues:
    - when the forum becomes bigger the transfer object will be huge
    - the flex will use huge client resources to create the presentation of the forum transfer object.
    So my question is what is your strategy/ design pattern for such a problem.
    An obvious answer would be create services that include the presentation logic and use transfor objects like ThreadListPage which will include only the first 10 threads.
    Thanks in advance

    I think you are going to get a few varied types of answers to a general question like this, but I will comment on a few things.  First, you should only be transmitting the data that you need to use or display to the user at the time.  If this forum was implemented in Flex (I wish) you wouldn't transfer the text for all the threads.  You might not transfer the thread text at all (just the subjects), you'd make calls back to the server to fetch that data when and if you need it.
    Also, I think you are overestimating the resources required for the Flex "presentation layer".  If you think about it, these workstations we have here are pretty idle most of the time when you're at a website.  Nowadays there's plenty of processing power just sitting there waiting, so as long as your design isn't flawed the CPU or memory are rarely going to be a bottleneck with Flex.
    The way I design, BlazeDS (or GraniteDS etc) should mostly just be "serving data".  There is some flexibility available, for example I don't see a problem with putting certain types of business rules (such as a limit on the number of results that can be recieved in a search) within server side code, and validation rules on the Flex side.  So there's not too many "industry standards" in Flex yet beyond maybe what's done in the various standard architectures, at least not that I'm aware of.
    You might find it beneficial to look into some of the various frameworks/architectures available like Cairngorm, Mate, Swiz, and so on.  Learning how they work (looking at examples) would probably answer some of your questions too.

Maybe you are looking for

  • TS1717 itunes won't open at all

    I cannot open ITunes at all on my computer. It used to work fine and I tried reinstalling and repairing and even plugging in the IPad and it still won't open. I tried opening it holding down control and shift and nothing. Any suggestions? I have an H

  • Export file too big! I need help.

    I am trying to export a text book from pdf to word.  How do I export a file if it is too big?  Is there a way to export half? Or export certain pages?  I am not computer savvy so this may have an easy solution.

  • Adobe Media Player failure solved

    Hi. I got this problem a few days ago. And today I´ve discovered why was the problem being caused. I had installed DivX on my laptop and that was causing a trouble betwenn Adobe Media Player and DivX Reproductor Video. That was a kind of conflict bet

  • Heading Change for keyfigures in the layouts

    Hi- We have two keyfigures in Manual Layouts which has short description as heading. Now users want to see Long description as heading. 1. I went to change mode of Manual layout and copied the "Long description" to heading. Still when users are creat

  • BB Desktop and ntlm auth.

    Hello, I have big problem :-) I need using BB Desktop in corporate network with proxy server with ntlm auth.  Desktop use proxy from IE bot not authorizing ntlm. Please helpme. Thx everyone