7 Replies - 15224 Views - Last Post: 20 December 2011 - 05:35 AM Rate Topic: -----

#1 greenpool   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 39
  • Joined: 27-November 11

how to compare if object exists in arraylist and add if doesn't

Posted 10 December 2011 - 06:43 PM

Hi guys,

i'm working on a library lending system..

the logic i'm using is:

1. get name you would like to lend the book to
2. if arraylist is empty, add person/set name
3. loop through peroson arraylist
3.1 compare person name
3.1.1 if person name matches then lend book
3.1.2 if person name doesn't match add person to arraylist
[go back to step 1]


here's my incomplete code:



	String name = "";
				boolean contd = true;
				Person p1 = new Person();
				Person p2 = new Person();
				while (contd) {

					if (name.equals("")) {
						System.out
								.print("Who would you like to lend the book to? ");
						name = keyboard.nextLine();
					}// if name is empty

					if (ml.getPeople().size() == 0) {

						p1.setName(name);
						ml.addPerson(p1);

					}// if database is empty, add person to person list

					// iterate through objects in array
					for (int i = 0; i < ml.getPeople().size(); i++) {

						Person aPerson = ml.getPeople().get(i);

						System.out.println("Person in database: "
								+ aPerson.getName());

						if (aPerson.getName().equals(name)) {

							// working to come later
							System.out
									.println("Book checked out to person successfully");

							// set name to an empty string so book can be lent
							// to another person
							name = "";

						}// if person name matches name entered

						else if (!aPerson.getName().equals(name)) {

							System.out
									.println("Person doesn't exist in the database. will add now..");

							p2.setName(name);
							ml.addPerson(p2);
							System.out.println("Done.");

						}// if person name doesn't match string entered

					}// for loop to iterate through list of people

					// print people in listed in array
					for (Person aPerson : ml.getPeople()) {

						System.out.println(aPerson.getName());
					}

				}// while contd is true






So on the first run this code segment adds the person object to the arraylist:

if (ml.getPeople().size() == 0) {

						p1.setName(name);
						ml.addPerson(p1);

					}// if database is empty, add person to person list




on the second run this code segment adds the person object to the arraylist:

else if (!aPerson.getName().equals(name)) {

							System.out
									.println("Person doesn't exist in the database. will add now..");

							p2.setName(name);
							ml.addPerson(p2);
							System.out.println("Done.");

						}// if person name doesn't match string entered



but on the 3rd run it doesn't work.

i belive on the 3rd run i'm modifying the details of p2 object rather than adding a new person.
now from what i gather if i had a p3 person object it'll work but thats not a solution since the more peopl i add, i'm gonna have to create more objects..or is that how its done? if so, how do i dyanamically create it? feeling really lost now :blink:


btw i'm making the assumption that the name's are unique.

appreciate any assistance!

thanks!

Is This A Good Question/Topic? 0
  • +

Replies To: how to compare if object exists in arraylist and add if doesn't

#2 Sheph   User is offline

  • D.I.C Lover
  • member icon

Reputation: 447
  • View blog
  • Posts: 1,032
  • Joined: 12-October 11

Re: how to compare if object exists in arraylist and add if doesn't

Posted 10 December 2011 - 11:03 PM

The problem is p2 is global and that it is really just a pointer, so when you set it's name, you are changing the value of the object already in the list.
else if (!aPerson.getName().equals(name)) {

	System.out.println("Person doesn't exist in the database. will add now..");
        Person dynamicPerson = new Person();
	dynamicPerson.setName(name);
	ml.addPerson(dynamicPerson);
	System.out.println("Done.");

}// if person name doesn't match string entered

Was This Post Helpful? 0
  • +
  • -

#3 greenpool   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 39
  • Joined: 27-November 11

Re: how to compare if object exists in arraylist and add if doesn't

Posted 11 December 2011 - 02:01 AM

Thanks i did get it work that way but now i've got the original question starring back at me.


here's the updated code:

if (option.equals("4")){
			
			
				String name = "";
				boolean contd = true;
				int personExists = 0;
				
				while (contd) {

					if (name.equals("")) {
						System.out
								.print("Who would you like to lend the book to? ");
						name = keyboard.nextLine();
						
						
						
					}// if name is empty

					if (ml.getPeople().size() == 0) {
						
						System.out
								.println("Database is empty. Will add person now");
						Person p1 = new Person();
						p1.setName(name);
						ml.addPerson(p1);
						System.out.println("Done.");

					}// if database is empty, add person to person list

					
					
					
					
					
					
					
					
					
					// iterate through objects in array
					for (int i = 0; i < ml.getPeople().size(); i++) {

						
						
						Person aPerson = ml.getPeople().get(i);

						System.out.println("Person in database: "
								+ aPerson.getName());

						if (aPerson.getName().equals(name)) {

							// working to come later
							System.out
									.println("Book checked out to person successfully");

							// set name to an empty string so book can be lent
							// to another person
							name = "";
							
                            
						}// if person name matches name entered

						
						
						
						
						else if (!aPerson.getName().equals(name)) {
						
						
							System.out
									.println("Person doesn't exist in the database. will add now..");

							
							
							Person p2 = new Person();
							p2.setName(name);
							ml.addPerson(p2);
							System.out.println("Done.");

						}// if person name doesn't match string entered

					}// for loop to iterate through list of people

					
					// print people in listed in array
					for (Person aPerson : ml.getPeople()) {

						System.out.println("Person in list:" + aPerson.getName());
					}
					
					
					
					
					

				} //while contd is true

		
		}




The problem with my code despite being able to add the first person and second person successfully is when i add the third person what happens is, it goes through each item in the arrayList and subsequently adds the new person 2 more times.

so for instance:
check if person name in the arrayList is the same
if not add person to the arrayList

[when the arrayList has 2 people, it will add the third person 3 times]


here's the output so that what i'm talking about makes sense:

Who would you like to lend the book to? Harry
Database is empty. Will add person now
Done.
Person in database: Harry
Book checked out to person successfully
Person in list:Harry
Who would you like to lend the book to? Sue
Person in database: Harry
Person doesn't exist in the database. will add now..
Done.
Person in database: Sue
Book checked out to person successfully
Person in list:Harry
Person in list:Sue
Who would you like to lend the book to? Dan
Person in database: Harry
Person doesn't exist in the database. will add now..
Done.
Person in database: Sue
Person doesn't exist in the database. will add now..
Done.
Person in database: Dan
Book checked out to person successfully
Person in database: Dan
Person doesn't exist in the database. will add now..
Done.
Person in database: 
Book checked out to person successfully
Person in list:Harry
Person in list:Sue
Person in list:Dan
Person in list:Dan
Person in list:
Who would you like to lend the book to? 




how can i do search of the entire arrayList by the person name and add the new person if it doesn't exist..?

any help is greatly appreciated!

THANKS!
Was This Post Helpful? 0
  • +
  • -

#4 GregBrannon   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2250
  • View blog
  • Posts: 5,340
  • Joined: 10-September 10

Re: how to compare if object exists in arraylist and add if doesn't

Posted 11 December 2011 - 05:17 AM

My observation is that you're doing too much in a single code clause or segment. Your original post included a reasonable approach:

Quote

1. get name you would like to lend the book to
2. if arraylist is empty, add person/set name
3. loop through peroson arraylist
3.1 compare person name
3.1.1 if person name matches then lend book
3.1.2 if person name doesn't match add person to arraylist

But the code you posted above that starts with "if (option.equals("4")" tries to nearly do it all. I recommend you break up your code into smaller pieces. Using your outline of the solution as a starting point:

1. get name you would like to lend the book to

Write a method, getBorrowerName(), that collects the library user's name from the keyboard and returns it.

2. if arraylist is empty, add person/set name

Write a method, findBorrowerName( name ), that returns the patron's ID number if the name entered already exists in the list of library patrons. If the name is not found, add the name using the method addBorrower( name ). (It doesn't matter if the list is empty.)

Write a method, addBorrower( name ), that adds a name to the list of library patrons, assigns an ID number, and returns the ID number.

3. loop through peroson arraylist
3.1 compare person name

This is done with findBorrowerName( name ), and it has already been done.

3.1.1 if person name matches then lend book

Write a method, lendBook( book, idNumber ), that checks out the argument book to the library patron identified by the argument ID number.

It seems that you'll also need a method to identify the book being checked out.

3.1.2 if person name doesn't match add person to arraylist

This has already been done.
---------------

Before writing a single line of code, thinking through the problem and writing down the possible solution's discrete steps as I've done above can be helpful. This serves to organize one's thoughts and define the approach to coding the solution.

You've written most of the code, but it's a bit disorganized and occasionally out of order, causing some unexpected results and then confusion. You have a good start so don't be discouraged, but you have a lot of code that now needs to be rethought and reorganized. Get to it.
Was This Post Helpful? 1
  • +
  • -

#5 greenpool   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 39
  • Joined: 27-November 11

Re: how to compare if object exists in arraylist and add if doesn't

Posted 19 December 2011 - 09:38 PM

Hi, so i took the advise and am trying to break the problem into smaller chunks.

All i'm trying to do now is check if a person exists or not.

1. if person exists, do nothing
2. if person doesn't exist, add person


here's what i've got so far:

if (option.equals("5")) {

				MyLibraryHelper helper = new MyLibraryHelper();

				System.out.println("Who do you want to lend the book to? ");
				String name = keyboard.nextLine();
				Person p1 = new Person();
				p1.setName(name);

				// if the arrayList is empty, add person
				if (ml.getPeople().size() == 0) {

					System.out.println(p1.getName()
							+ " doesn't exist in database. Adding now..");

					ml.addPerson(p1);

					if (ml.getPeople().contains(p1)) {

						System.out
								.println("Person has been successfully added");
					}

				}

				else {

					// check if person exists
					helper.checkIfPersonExists(p1, ml);

				}

				// print list of people names
				for (Person aPerson : ml.getPeople()) {

					System.out.println(aPerson.getName());

				}// run through people list

			}




helper.checkIfPersonExists(p1, ml) makes a call to:


public void checkIfPersonExists(Person p1, MyLibrary ml) {

if (ml.getPeople().contains(p1)) {

			System.out.println(p1.getName() + " already exists in database");

		}

		//if person doesn't exist - add
		else if (! ml.getPeople().contains(p1)) {
			System.out.println(p1.getName()
					+ " doesn't exist in database. Adding now..");

			ml.addPerson(p1);

			if (ml.getPeople().contains(p1)) {

				System.out.println("Person has been successfully added");

			}

		}

	}






i've also tried changing the if staments above to:

ml.getPeople().contains(p1.getName())  //to check by name



i can't seem to figure out how to NOT add the person if they exist. it doesn't seem to work :s

ml is the MyLibrary object and the getPeople() returns the arrayList of people.



Any advice or help is appreciated, thanks!
Was This Post Helpful? 0
  • +
  • -

#6 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8381
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: how to compare if object exists in arraylist and add if doesn't

Posted 19 December 2011 - 09:44 PM

ArrayList also have a contains(Object) method
you are complicating your life or it is a school assigment ?
Was This Post Helpful? 0
  • +
  • -

#7 greenpool   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 39
  • Joined: 27-November 11

Re: how to compare if object exists in arraylist and add if doesn't

Posted 19 December 2011 - 10:27 PM

View Postpbl, on 19 December 2011 - 09:44 PM, said:

ArrayList also have a contains(Object) method
you are complicating your life or it is a school assigment ?


Nah not a school assignment. just doing this to learn java.

i did manage to get it working by looping through and comparing but i now i'm curious to know how the contains method works cos i couldn't get it working : /


Here's how i did it:

if (option.equals("5")) {

				MyLibraryHelper helper = new MyLibraryHelper();
				boolean personExists = false;

				System.out.println("Who do you want to lend the book to? ");
				String name = keyboard.nextLine();
				Person p1 = new Person();
				p1.setName(name);

				// if the arrayList is empty, add person
				if (ml.getPeople().size() == 0) {

					System.out.println(p1.getName()
							+ " doesn't exist in database. Adding now..");

					ml.addPerson(p1);

					if (ml.getPeople().contains(p1)) {

						System.out
								.println("Person has been successfully added");
					}

				}

				else if (ml.getPeople().size() > 0) {

					// check if person exists
					personExists = helper.checkIfPersonExists(p1, ml);

					if (personExists == true) {

						System.out.println("Person already exists");

					} else if (personExists == false) {

						System.out.println(p1.getName()
								+ " doesn't exist in database. Adding now..");

						ml.addPerson(p1);

						System.out.println("Done.");

					}

				}
}









calling personExists = helper.checkIfPersonExists(p1, ml):

public boolean checkIfPersonExists(Person p1, MyLibrary ml) {

		boolean valid = false;
		String temp = null;
		
		
		for(int i=0;i<ml.getPeople().size();i++){
			
			temp=ml.getPeople().get(i).getName();
			
			if (p1.getName().equals(temp)){
				
				valid=true;
				
				
			}
			
			
			
		}

		return valid;

}



Was This Post Helpful? 0
  • +
  • -

#8 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8381
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: how to compare if object exists in arraylist and add if doesn't

Posted 20 December 2011 - 05:35 AM

Your Person class should overload the equals() method

class Person {

   private String name;

   public boolean equals(Object o) {
      Person other = (Person) o;
      return name.equals(other.name);
   }
}


So when the ArrayList contains() method will call get[N].equals(param) your Person class will return true/false based on the Person name
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1