This discussion is archived
9 Replies Latest reply: Apr 13, 2008 10:41 PM by 807591 RSS

How can i check to see if an object is already in the array list?

807591 Newbie
Currently Being Moderated
while (res.next()) {

                Schedule schedule = new Schedule();
                
                customerName = res.getString("CUSTOMERNAME");
                schedule.setCustomerName(customerName);
                
                magName = res.getString("MAGNAME");
                schedule.setMagName(magName);
                
             
                System.out.println("NAME: " + customerName);
                System.out.println("MAGNAME: " + magName);
                
                if(!scheduleListH.contains(schedule))  //this won't work
                    scheduleListH.add(schedule);
            }
schedule object has 2 fields, customerName and MagName;

Basically i want to say, IF the scheudleList (which is an array list) contains an object schedule that has the same customerName and MagName as any of the objects in the array list, don't readd the object.

ANy help would be great!
  • 1. Re: How can i check to see if an object is already in the array list?
    807591 Newbie
    Currently Being Moderated
    You can use the [contains(Object)|http://java.sun.com/j2se/1.4.2/docs/api/java/util/List.html#contains(java.lang.Object)] method ( making sure whatever objects you're adding have overridden the equals() and hashCode() methods ).

    Or you can simply use a Set instead, but you still need to implement equals() and hashCode().

    Edit

    After fully reading your post, I went back and bolded a phrase.

    Edited by: endasil on 13-Apr-2008 11:57 PM
  • 2. Re: How can i check to see if an object is already in the array list?
    807591 Newbie
    Currently Being Moderated
    THanks for the responce...
    Well in theory they will be different objects...so that wouldnt work because you could have 2 objects with the same data, but they would be different objects in memory.

    I think a set will also fail in this solution because, or will the set check the data members? for example, if i have 2 objects:
    Schedule s1 = new Schedule("Cory","Hudini");
    Scheduel s2 = new Schedule("Cory","Hudini");

    will a set only allow 1 of these in there? if so i will use a set.

    I wrote this but I wans't sure why this wouldn't work, logically it makes sense.
       for(int i= 0; i < scheduleListH.size(); i++)
                    {
                        if((scheduleListH.get(i).getCustomerName().equals(customerName)) && (scheduleListH.get(i).getMagName().equals(magName)))
                            ;
                        else
                            scheduleListH.add(schedule);
                    }
    Edited by: lokie on Apr 14, 2008 4:02 AM

    NOTE: after re-reading your edit I see that a set would also require overloading both methods.
    Is there a way, to do this without overloading, like for example, I don't really care if the objects are equal thats why I don't understand why hashCode() needs to be overriden.
    I want to compare whats in the object, even if they are 2 different objects, if they have the same data I don't want to re-add them.
    SO basically i just want to compare the contains of 2 objects, if the customerName and magician name equal whwat is already in the object, don't add to the list. My code above I thought is doing that isn't it? but when I run it, it still adds them.

    Edited by: lokie on Apr 14, 2008 4:11 AM
  • 3. Re: How can i check to see if an object is already in the array list?
    807591 Newbie
    Currently Being Moderated
    lokie wrote:
    My code above I thought is doing that isn't it? but when I run it, it still adds them.
    Well, no...in fact your code adds the second object every time it comes across a different element. Therefore, as long as there is one element that isn't the same as your object, you're adding it...and most likely multiple times.

    Don't be afraid of writing equals() methods. It's a necessary practice. For now, if you don't want to override hashCode(), that's OK. But you really need to get in the habit (otherwise when people use your objects in a HashSet or HashMap, it won't function properly).

    Here's an example equals method: this is all it takes!
    public class MyObject {
       private String data1, data2;
       public boolean equals ( Object other ) { 
          if ( other != null && other instanceof MyObject ) {  //this step will pretty much stay the same for any object
              MyObject that = (MyObject)other;
              return ( this.data1 == that.data1 || (this.data1 != null && this.data1.equals(that.data1) ) //first object checked
                 &&  //both have to be checked, so AND them
                 ( this.data2 == that.data2 || (this.data2 != null && this.data2.equals(that.data2) ) ; //second object checked
          } else { 
              return false;
          }
       }
    }
    That's it! Here's what it's doing:
    1. If other is null or is not an instance of MyObject, return false as they can't be equal
    2. Obtain a reference of type MyObject to other, call it "that"
    3. Return true if:
    For each piece of data, either this' version is null AND that's version is null, or this.data = that.data.

    Then eventually learn to use hashCode, we'll forgive you if you don't do that here though.
  • 4. Re: How can i check to see if an object is already in the array list?
    807591 Newbie
    Currently Being Moderated
    Thanks a ton i tried that out, but still no luck, I see my flaw now in that loop and I thought this would fix it..
    basically i search through all the objects in the list, if 1 object is found that matches the object in the list, it will break out, and not add it to the list, if it isn't found by the end of the loop it should add it.


    here's the code:
                  for(int i= 0; i < scheduleListH.size(); i++)
                    {
                        if(scheduleListH.get(i).equals(schedule))
                        {
                            isFound = true;
                            break;
                        }
                        
                    }
                    if(!isFound)
                     scheduleListH.add(schedule);
    public class Schedule {
    
        //  private ArrayList
        private String customerName;
        private String holidayName;        //note, i don't carea bout the holiday name
        private String magName;
    
          public boolean equals ( Object other ) { 
          if ( other != null && other instanceof Schedule ) {  //this step will pretty much stay the same for any object
              Schedule that = (Schedule)other;
              return (this.customerName != null ? this.customerName.equals(that.customerName) : that.customerName == null) //first object checked
                 &&  //both have to be checked, so AND them
                 (this.magName != null ? this.magName.equals(that.magName) : that.magName == null); //second object checked
          } else { 
              return false;
          }
       }
    }
        
    Edited by: lokie on Apr 14, 2008 4:46 AM
  • 5. Re: How can i check to see if an object is already in the array list?
    807591 Newbie
    Currently Being Moderated
    lokie wrote:
    Thanks a ton i tried that out, but still no luck.
    Well, now that you've implemented your equals() method you should be able to use contains() without any problem. I'm curious, though, what isn't working about your current solution? Are you getting compile errors? What's happening?
  • 6. Re: How can i check to see if an object is already in the array list?
    807591 Newbie
    Currently Being Moderated
    Thanks!
    Oops I forogt I could use the .contains, i also tried that but still no luck.
    There is no compiler error but here is an example of the output:
    Populating scheudle list for HOLIDAY selection data structure:  
    NAME: Cory
    MAGNAME: Merlin
    NAME: Brandon
    MAGNAME: Gondorf
    NAME: Chris
    MAGNAME: Houdini
    NAME: Lokie
    MAGNAME: Blaine
    Sample SCHEDUEL H [Cory          Merlin, Brandon          Gondorf, Chris          Houdini, Lokie          Blaine]
    As you can see, There are 4 objects in the array list:
    Cory Merlin
    Brandon Gondorf
    Chris Houdini
    Lokie BLaine

    Now this function is called everytime the user choses a new item in a combo box.
    So if they go back to the previous selection, Holiday's, it shouldn't read add all the orginal things.

    But if I go up and select the same item in the combo box it changes whats in the array list to the following:
    Populating scheudle list for HOLIDAY selection data structure:  
    NAME: Cory
    MAGNAME: Merlin
    NAME: Brandon
    MAGNAME: Gondorf
    NAME: Chris
    MAGNAME: Houdini
    NAME: Lokie
    MAGNAME: Blaine
    Sample SCHEDUEL H [Cory          Merlin, Brandon          Gondorf, Chris          Houdini, Lokie          Blaine, Cory          Merlin, Brandon          Gondorf, Chris          Houdini, Lokie          Blaine]
    Here's my whole function if your interested and where I call it:
        void populateSchedule(String holiday) {
            Statement sta = null;
            Connection connection6 = null;
    
    
            try {
                connection6 = DriverManager.getConnection(URL, USERNAME, PASSWORD);
                sta = connection6.createStatement();
                //getting the list of magicians from the selected holiday to see if any are free
                ResultSet res = sta.executeQuery(
                        "SELECT CUSTOMERNAME, MAGNAME FROM SCHEDULE WHERE HOLIDAYNAME = '" + holiday + "'");
    
                String customerName = " ";
                String magName = " ";
    
    
                System.out.println("Populating scheudle list for HOLIDAY selection data structure:  ");
    
                //this is where I add the waiting list objects to the array that will later be used
                //to print out and shown to the user when they select the waiting list status
                while (res.next()) {
    
                    Schedule schedule = new Schedule();
                    
                    customerName = res.getString("CUSTOMERNAME");
                    schedule.setCustomerName(customerName);
                    
                    magName = res.getString("MAGNAME");
                    schedule.setMagName(magName);
                    
                 
                    System.out.println("NAME: " + customerName);
                    System.out.println("MAGNAME: " + magName);
                    
                    
                          
                   if(!scheduleListH.contains(schedule))
                       scheduleListH.add(schedule);
     }
                
    
                System.out.println("Sample SCHEDUEL H " +   scheduleListH);
    
    
            } catch (SQLException ex) {
                System.out.println(ex);
                ex.printStackTrace();
            } finally {
                try {
    
                    sta.close();
                    connection6.close();
                } catch (SQLException ex) {
                    Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
    
        }
    //this is where i call in the GUI
        private void specStatusComboBoxActionPerformed(java.awt.event.ActionEvent evt) {                                                   
            // TODO add your handling code here:
            String selectedItem = (String)specStatusComboBox.getSelectedItem();
            String groupSelectedItem = (String) groupStatusComboBox.getSelectedItem();
            
            if(groupSelectedItem.equals("Holidays"))
            {
                //get customer name and magician name from the Scheduel table
                //use selectedItem (it will be a holiday name)
                //magicDB.clearScheduleHList();
                magicDB.populateSchedule(selectedItem);
                ArrayList<Schedule> tempScheduleList = magicDB.getScheduleHListCopy();
                outputTextArea.setText(" ");
                outputTextArea.setText("CUSTOMER NAME" +"\t\t" + "MAGICIAN NAME" + "\n");
                for(int i = 0; i < tempScheduleList.size(); i++)
                    outputTextArea.append(tempScheduleList.get(i).toString() + "\n");
            }
            
        }   
    I'll reward the duke stars anyways because you have been a great help either way!
  • 7. Re: How can i check to see if an object is already in the array list?
    807591 Newbie
    Currently Being Moderated
    Wow very strange....
    I'm not sure what happened but after thinking about it, i could just clear the array if it contains anything and repopulate it, hence, there will never be duplicates
    the following line fixed it:
       if(!scheduleListH.isEmpty())
                    scheduleListH.clear();
                
                while (res.next()) {
    
                    Schedule schedule = new Schedule();
                    
                    customerName = res.getString("CUSTOMERNAME");
                    schedule.setCustomerName(customerName);
                    
                    magName = res.getString("MAGNAME");
                    schedule.setMagName(magName);
                    
                 
                    System.out.println("NAME: " + customerName);
                    System.out.println("MAGNAME: " + magName);
                    
                    
                //i don't need this now          
                //   if(!scheduleListH.contains(schedule)) 
                       scheduleListH.add(schedule);
    I still learned somthing so thats good ^-^
  • 8. Re: How can i check to see if an object is already in the array list?
    807591 Newbie
    Currently Being Moderated
    Forget your big program for now--the trick to managing big programs is to test the little changes thoroughly before adding them.

    Try this tester for your schedule class (add imports if you need them). What does it output?
    public class Tester {
    
       public static void main(String[] args) {
           List<Schedule> list = new ArrayList<Schedule>();
           
           Schedule s1, s2, s3;
           s1 = new Schedule();
           s1.setCustomerName("CN");
           s1.setMagName("MN");
    
           s2 = new Schedule();
           s2.setCustomerName("CN");
           s2.setMagName("MN");
    
           s3 = new Schedule();
           s3.setCustomerName("blah");
           s3.setMagName("blah");
           
           list.add(s1);
           if ( list.contains(s1) ) { System.out.println("list contained s1"); }
           if ( list.contains(s2) ) { System.out.println("list contained s2"); }
           if ( list.contains(s3) ) { System.out.println("list contained s3"); }
                 
    
       }
    }
    If your equals method is working correctly, this should print:
    list contained s1
    list contained s2
    So what does it print?

    edit Didn't see your last post before posting, but you should still make sure your equals method works properly! So try this anyway!

    Edited by: endasil on 14-Apr-2008 1:23 AM
  • 9. Re: How can i check to see if an object is already in the array list?
    807591 Newbie
    Currently Being Moderated
    yep it worked great!
    it seems there must have been some other factor, not the equals()...
    This program is getting huge, who knows what happened hah, kind of scary.