Results 1 to 3 of 3
  1. #1
    monkeyhead is offline Member
    Join Date
    Oct 2011
    Posts
    9
    Rep Power
    0

    Default Preventing duplicate instances of an object

    Hi there,
    I'm presently dabbling with association and hit a wall.

    For example:-
    Java Code:
            Player one = new Player(12345678, "Dave", "1 A Street");
            Player two = new Player(12345678, "Dave", "1 A Street");

    What is the best way to prevent a new instance of player being created with the same parameters of an instance that already exists?

    Because what I'm aiming to do is to create a new a player based upon user input, but I don't want the user to create a player that already exists.

    I'm storing them in an array list too.

    Many thanks for any advice,

    Monkeyhead

  2. #2
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: Preventing duplicate instances of an object

    Override the equals(...) method and store references to created objects in a Set.
    Get in the habit of using standard Java naming conventions!

  3. #3
    FallenBlade is offline Member
    Join Date
    Mar 2010
    Posts
    31
    Rep Power
    0

    Default Re: Preventing duplicate instances of an object

    You could loop through your array list and check if there is already a player with those details before adding the new player.

Similar Threads

  1. Counting/tracking instances of an Object problem
    By ozzyman in forum New To Java
    Replies: 2
    Last Post: 04-03-2011, 02:02 AM
  2. Cannot insert duplicate key row in object
    By losintikfos in forum New To Java
    Replies: 3
    Last Post: 05-07-2009, 10:43 AM
  3. Calling a method for all instances of an object
    By rattle in forum New To Java
    Replies: 4
    Last Post: 04-30-2008, 03:10 PM
  4. Object Reflection: Creating new instances
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-23-2008, 09:13 PM
  5. Naming object instances
    By oldgit in forum New To Java
    Replies: 9
    Last Post: 02-08-2008, 12:18 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •