java: ensure that there is only one instance of the typeIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?Does a finally block always get executed in Java?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?How do I determine whether an array contains a particular value in Java?How do I convert a String to an int in Java?Creating a memory leak with Java

Function of the separated, individual solar cells on Telstar 1 and 2? Why were they "special"?

Why wasn't Linda Hamilton in T3?

An alternative to "two column" geometry proofs

How to run a command 1 out of N times in Bash

Can authors email you PDFs of their textbook for free?

Can a system of three stars exist?

Can my UK debt be collected because I have to return to US?

If the government illegally doesn't ask for article 50 extension, can parliament do it instead?

Why do modes sound so different, although they are basically the same as a mode of another scale?

Is there anything in the universe that cannot be compressed?

Was there an original & definitive use of alternate dimensions/realities in fiction?

Cheap oscilloscope showing 16 MHz square wave

Ways you can end up paying interest on a credit card if you pay the full amount back in due time

Is Borg adaptation only temporary?

The 7-numbers crossword

Cannot add javascript to footer

Why didn't Thatcher give Hong Kong to Taiwan?

Are there balance issues when allowing attack of opportunity against any creature?

How do I get my neighbour to stop disturbing with loud music?

Why do we need explainable AI?

Replace a motion-sensor/timer with simple single pole switch

Colored grid with coordinates on all sides?

New coworker has strange workplace requirements - how should I deal with them?

How can I store milk for long periods of time?



java: ensure that there is only one instance of the type


Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?Does a finally block always get executed in Java?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?How do I determine whether an array contains a particular value in Java?How do I convert a String to an int in Java?Creating a memory leak with Java






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am following the example from:
https://www.baeldung.com/java-composite-pattern



public class FinancialDepartment implements Department 

private Integer id;
private String name;

public void printDepartmentName()
System.out.println(getClass().getSimpleName());


// standard constructor, getters, setters

public class SalesDepartment implements Department

private Integer id;
private String name;

public void printDepartmentName()
System.out.println(getClass().getSimpleName());


// standard constructor, getters, setters


public class HeadDepartment implements Department
private Integer id;
private String name;

private List<Department> childDepartments;

public HeadDepartment(Integer id, String name)
this.id = id;
this.name = name;
this.childDepartments = new ArrayList<>();


public void printDepartmentName()
childDepartments.forEach(Department::printDepartmentName);


public void addDepartment(Department department)
childDepartments.add(department);


public void removeDepartment(Department department)
childDepartments.remove(department);




I want to prevent my self from able to add two of the same types to HeadDepartment



for example if it call add addDepartment twice for the same type, there should be only one



public class CompositeDemo 
public static void main(String args[])
Department salesDepartment = new SalesDepartment(
1, "Sales department");

Department salesDepartment2 = new SalesDepartment(
1, "Sales department");
Department salesDepartment3 = new SalesDepartment(
3, "Sales department");


Department financialDepartment = new FinancialDepartment(
2, "Financial department");

HeadDepartment headDepartment = new HeadDepartment(
3, "Head department");

headDepartment.addDepartment(salesDepartment);
headDepartment.addDepartment(financialDepartment);

// only keep the latest of same instanceof ie replace
headDepartment.addDepartment(salesDepartment2);
headDepartment.addDepartment(salesDepartment3);

// this should only print twice one for salesDepartment3 and financialDepartment
headDepartment.printDepartmentName();





i suppose do i just iterate the list and if instanceof, replace and put?



public void addDepartment(Department department) 
childDepartments.add(department);



i would like to keep the order as well if the instnaceof Department was the first, i would like it to keep it as 1st, meaning it should print salesDepartment3 before financialDepartment










share|improve this question
























  • What happens if addDepartment is called once with SalesDepartment and then again with Something extends SalesDepartment? You want to replace the former with the latter or want to keep them both?

    – khachik
    Mar 28 at 1:04











  • Use a Set? (e.g. LinkedHashSet).

    – Elliott Frisch
    Mar 28 at 1:08











  • @khachik say that's not a valid case at this moment that nothing will extend Department beyond its implementation. but if it would be easier then Something extend SalesDepartement is still SalesDepartment so replace it

    – ealeon
    Mar 28 at 1:17












  • if it is not the case then you can maintain a map of Class -> instance and add departments by their class. If you want to support hierarchy then you need to get the top parent class that is below Department in the hierarchy and use it as a key.

    – khachik
    Mar 28 at 2:22











  • @ElliottFrisch but a Set wouldnt be able to discern between the same instanceof but with different constructor parameters. it will keep all of salesDepartment2 because of different id

    – ealeon
    Mar 28 at 6:22

















0















I am following the example from:
https://www.baeldung.com/java-composite-pattern



public class FinancialDepartment implements Department 

private Integer id;
private String name;

public void printDepartmentName()
System.out.println(getClass().getSimpleName());


// standard constructor, getters, setters

public class SalesDepartment implements Department

private Integer id;
private String name;

public void printDepartmentName()
System.out.println(getClass().getSimpleName());


// standard constructor, getters, setters


public class HeadDepartment implements Department
private Integer id;
private String name;

private List<Department> childDepartments;

public HeadDepartment(Integer id, String name)
this.id = id;
this.name = name;
this.childDepartments = new ArrayList<>();


public void printDepartmentName()
childDepartments.forEach(Department::printDepartmentName);


public void addDepartment(Department department)
childDepartments.add(department);


public void removeDepartment(Department department)
childDepartments.remove(department);




I want to prevent my self from able to add two of the same types to HeadDepartment



for example if it call add addDepartment twice for the same type, there should be only one



public class CompositeDemo 
public static void main(String args[])
Department salesDepartment = new SalesDepartment(
1, "Sales department");

Department salesDepartment2 = new SalesDepartment(
1, "Sales department");
Department salesDepartment3 = new SalesDepartment(
3, "Sales department");


Department financialDepartment = new FinancialDepartment(
2, "Financial department");

HeadDepartment headDepartment = new HeadDepartment(
3, "Head department");

headDepartment.addDepartment(salesDepartment);
headDepartment.addDepartment(financialDepartment);

// only keep the latest of same instanceof ie replace
headDepartment.addDepartment(salesDepartment2);
headDepartment.addDepartment(salesDepartment3);

// this should only print twice one for salesDepartment3 and financialDepartment
headDepartment.printDepartmentName();





i suppose do i just iterate the list and if instanceof, replace and put?



public void addDepartment(Department department) 
childDepartments.add(department);



i would like to keep the order as well if the instnaceof Department was the first, i would like it to keep it as 1st, meaning it should print salesDepartment3 before financialDepartment










share|improve this question
























  • What happens if addDepartment is called once with SalesDepartment and then again with Something extends SalesDepartment? You want to replace the former with the latter or want to keep them both?

    – khachik
    Mar 28 at 1:04











  • Use a Set? (e.g. LinkedHashSet).

    – Elliott Frisch
    Mar 28 at 1:08











  • @khachik say that's not a valid case at this moment that nothing will extend Department beyond its implementation. but if it would be easier then Something extend SalesDepartement is still SalesDepartment so replace it

    – ealeon
    Mar 28 at 1:17












  • if it is not the case then you can maintain a map of Class -> instance and add departments by their class. If you want to support hierarchy then you need to get the top parent class that is below Department in the hierarchy and use it as a key.

    – khachik
    Mar 28 at 2:22











  • @ElliottFrisch but a Set wouldnt be able to discern between the same instanceof but with different constructor parameters. it will keep all of salesDepartment2 because of different id

    – ealeon
    Mar 28 at 6:22













0












0








0








I am following the example from:
https://www.baeldung.com/java-composite-pattern



public class FinancialDepartment implements Department 

private Integer id;
private String name;

public void printDepartmentName()
System.out.println(getClass().getSimpleName());


// standard constructor, getters, setters

public class SalesDepartment implements Department

private Integer id;
private String name;

public void printDepartmentName()
System.out.println(getClass().getSimpleName());


// standard constructor, getters, setters


public class HeadDepartment implements Department
private Integer id;
private String name;

private List<Department> childDepartments;

public HeadDepartment(Integer id, String name)
this.id = id;
this.name = name;
this.childDepartments = new ArrayList<>();


public void printDepartmentName()
childDepartments.forEach(Department::printDepartmentName);


public void addDepartment(Department department)
childDepartments.add(department);


public void removeDepartment(Department department)
childDepartments.remove(department);




I want to prevent my self from able to add two of the same types to HeadDepartment



for example if it call add addDepartment twice for the same type, there should be only one



public class CompositeDemo 
public static void main(String args[])
Department salesDepartment = new SalesDepartment(
1, "Sales department");

Department salesDepartment2 = new SalesDepartment(
1, "Sales department");
Department salesDepartment3 = new SalesDepartment(
3, "Sales department");


Department financialDepartment = new FinancialDepartment(
2, "Financial department");

HeadDepartment headDepartment = new HeadDepartment(
3, "Head department");

headDepartment.addDepartment(salesDepartment);
headDepartment.addDepartment(financialDepartment);

// only keep the latest of same instanceof ie replace
headDepartment.addDepartment(salesDepartment2);
headDepartment.addDepartment(salesDepartment3);

// this should only print twice one for salesDepartment3 and financialDepartment
headDepartment.printDepartmentName();





i suppose do i just iterate the list and if instanceof, replace and put?



public void addDepartment(Department department) 
childDepartments.add(department);



i would like to keep the order as well if the instnaceof Department was the first, i would like it to keep it as 1st, meaning it should print salesDepartment3 before financialDepartment










share|improve this question














I am following the example from:
https://www.baeldung.com/java-composite-pattern



public class FinancialDepartment implements Department 

private Integer id;
private String name;

public void printDepartmentName()
System.out.println(getClass().getSimpleName());


// standard constructor, getters, setters

public class SalesDepartment implements Department

private Integer id;
private String name;

public void printDepartmentName()
System.out.println(getClass().getSimpleName());


// standard constructor, getters, setters


public class HeadDepartment implements Department
private Integer id;
private String name;

private List<Department> childDepartments;

public HeadDepartment(Integer id, String name)
this.id = id;
this.name = name;
this.childDepartments = new ArrayList<>();


public void printDepartmentName()
childDepartments.forEach(Department::printDepartmentName);


public void addDepartment(Department department)
childDepartments.add(department);


public void removeDepartment(Department department)
childDepartments.remove(department);




I want to prevent my self from able to add two of the same types to HeadDepartment



for example if it call add addDepartment twice for the same type, there should be only one



public class CompositeDemo 
public static void main(String args[])
Department salesDepartment = new SalesDepartment(
1, "Sales department");

Department salesDepartment2 = new SalesDepartment(
1, "Sales department");
Department salesDepartment3 = new SalesDepartment(
3, "Sales department");


Department financialDepartment = new FinancialDepartment(
2, "Financial department");

HeadDepartment headDepartment = new HeadDepartment(
3, "Head department");

headDepartment.addDepartment(salesDepartment);
headDepartment.addDepartment(financialDepartment);

// only keep the latest of same instanceof ie replace
headDepartment.addDepartment(salesDepartment2);
headDepartment.addDepartment(salesDepartment3);

// this should only print twice one for salesDepartment3 and financialDepartment
headDepartment.printDepartmentName();





i suppose do i just iterate the list and if instanceof, replace and put?



public void addDepartment(Department department) 
childDepartments.add(department);



i would like to keep the order as well if the instnaceof Department was the first, i would like it to keep it as 1st, meaning it should print salesDepartment3 before financialDepartment







java oop composite






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 28 at 0:55









ealeonealeon

4,80211 gold badges49 silver badges102 bronze badges




4,80211 gold badges49 silver badges102 bronze badges















  • What happens if addDepartment is called once with SalesDepartment and then again with Something extends SalesDepartment? You want to replace the former with the latter or want to keep them both?

    – khachik
    Mar 28 at 1:04











  • Use a Set? (e.g. LinkedHashSet).

    – Elliott Frisch
    Mar 28 at 1:08











  • @khachik say that's not a valid case at this moment that nothing will extend Department beyond its implementation. but if it would be easier then Something extend SalesDepartement is still SalesDepartment so replace it

    – ealeon
    Mar 28 at 1:17












  • if it is not the case then you can maintain a map of Class -> instance and add departments by their class. If you want to support hierarchy then you need to get the top parent class that is below Department in the hierarchy and use it as a key.

    – khachik
    Mar 28 at 2:22











  • @ElliottFrisch but a Set wouldnt be able to discern between the same instanceof but with different constructor parameters. it will keep all of salesDepartment2 because of different id

    – ealeon
    Mar 28 at 6:22

















  • What happens if addDepartment is called once with SalesDepartment and then again with Something extends SalesDepartment? You want to replace the former with the latter or want to keep them both?

    – khachik
    Mar 28 at 1:04











  • Use a Set? (e.g. LinkedHashSet).

    – Elliott Frisch
    Mar 28 at 1:08











  • @khachik say that's not a valid case at this moment that nothing will extend Department beyond its implementation. but if it would be easier then Something extend SalesDepartement is still SalesDepartment so replace it

    – ealeon
    Mar 28 at 1:17












  • if it is not the case then you can maintain a map of Class -> instance and add departments by their class. If you want to support hierarchy then you need to get the top parent class that is below Department in the hierarchy and use it as a key.

    – khachik
    Mar 28 at 2:22











  • @ElliottFrisch but a Set wouldnt be able to discern between the same instanceof but with different constructor parameters. it will keep all of salesDepartment2 because of different id

    – ealeon
    Mar 28 at 6:22
















What happens if addDepartment is called once with SalesDepartment and then again with Something extends SalesDepartment? You want to replace the former with the latter or want to keep them both?

– khachik
Mar 28 at 1:04





What happens if addDepartment is called once with SalesDepartment and then again with Something extends SalesDepartment? You want to replace the former with the latter or want to keep them both?

– khachik
Mar 28 at 1:04













Use a Set? (e.g. LinkedHashSet).

– Elliott Frisch
Mar 28 at 1:08





Use a Set? (e.g. LinkedHashSet).

– Elliott Frisch
Mar 28 at 1:08













@khachik say that's not a valid case at this moment that nothing will extend Department beyond its implementation. but if it would be easier then Something extend SalesDepartement is still SalesDepartment so replace it

– ealeon
Mar 28 at 1:17






@khachik say that's not a valid case at this moment that nothing will extend Department beyond its implementation. but if it would be easier then Something extend SalesDepartement is still SalesDepartment so replace it

– ealeon
Mar 28 at 1:17














if it is not the case then you can maintain a map of Class -> instance and add departments by their class. If you want to support hierarchy then you need to get the top parent class that is below Department in the hierarchy and use it as a key.

– khachik
Mar 28 at 2:22





if it is not the case then you can maintain a map of Class -> instance and add departments by their class. If you want to support hierarchy then you need to get the top parent class that is below Department in the hierarchy and use it as a key.

– khachik
Mar 28 at 2:22













@ElliottFrisch but a Set wouldnt be able to discern between the same instanceof but with different constructor parameters. it will keep all of salesDepartment2 because of different id

– ealeon
Mar 28 at 6:22





@ElliottFrisch but a Set wouldnt be able to discern between the same instanceof but with different constructor parameters. it will keep all of salesDepartment2 because of different id

– ealeon
Mar 28 at 6:22












1 Answer
1






active

oldest

votes


















2















Your addDepartment() needs to iterate over the list of children and compare each one's class to the class of the object you are adding.
Pseudo code:



Class addClass = itemToAdd.getClass();
for each child
{
if (child.getClass() == addClass)

//class is already in the list so replace it.






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55388627%2fjava-ensure-that-there-is-only-one-instance-of-the-type%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2















    Your addDepartment() needs to iterate over the list of children and compare each one's class to the class of the object you are adding.
    Pseudo code:



    Class addClass = itemToAdd.getClass();
    for each child
    {
    if (child.getClass() == addClass)

    //class is already in the list so replace it.






    share|improve this answer





























      2















      Your addDepartment() needs to iterate over the list of children and compare each one's class to the class of the object you are adding.
      Pseudo code:



      Class addClass = itemToAdd.getClass();
      for each child
      {
      if (child.getClass() == addClass)

      //class is already in the list so replace it.






      share|improve this answer



























        2














        2










        2









        Your addDepartment() needs to iterate over the list of children and compare each one's class to the class of the object you are adding.
        Pseudo code:



        Class addClass = itemToAdd.getClass();
        for each child
        {
        if (child.getClass() == addClass)

        //class is already in the list so replace it.






        share|improve this answer













        Your addDepartment() needs to iterate over the list of children and compare each one's class to the class of the object you are adding.
        Pseudo code:



        Class addClass = itemToAdd.getClass();
        for each child
        {
        if (child.getClass() == addClass)

        //class is already in the list so replace it.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 28 at 1:02









        John3136John3136

        25.1k3 gold badges37 silver badges61 bronze badges




        25.1k3 gold badges37 silver badges61 bronze badges





















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55388627%2fjava-ensure-that-there-is-only-one-instance-of-the-type%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript