Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

check if an object exists in an ArrayList

807603Dec 6 2007 — edited Dec 6 2007
I got an ArrayList in which I save new objects.

If an object already exists, I want the program to tell me that. The unique identifier is the object�s name.
switch(command) {
case 1:
	System.out.print("A name please: ");
	String name = sc.nextLine();
	for(int i=0; i<allObjects.size(); i++)
	{
		if(allObjects.get(i).getName().equals(name))
		{
			System.out.print("Name already exists");

		}
		else
		{
			allObjects.add(new Customer(name));
		}
		break;
         }
The problem is that the program does not add the new object to the ArrayList if the person does not exist. Why doesn�t the program add the object to the ArrayList?

If I put the line allObjects.add(new Customer(name)); outside the if-statement in case 1, then it adds the object. Why does not the if-statement work?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 3 2008
Added on Dec 6 2007
11 comments
1,891 views