Java address book. How to prevent duplicate contacts in my code?
switch(menuChoice) {
case 1:
System.out.println("Enter your contact's first name:n");
String fname = scnr.next();
System.out.println("Enter your contact's last name:n");
String lname = scnr.next();
Necronomicon.addContact(new Person(fname, lname));
break;
// main truncated here for readability
import java.util.ArrayList;
public class AddressBook {
ArrayList<Person> ArrayOfContacts= new ArrayList<Person>();
public void addContact(Person p) {
ArrayOfContacts.add(p);
/*
for(int i = 0; i < ArrayOfContacts.size(); i++) {
if(ArrayOfContacts.get(i).getID() != p.getID())
ArrayOfContacts.add(p);
else
System.out.println("Sorry this contact already exists.");
}
*/
}
}
public class Person {
private String fName = null;
private String lName = null;
private static int ID = 1000;
public Person(String fName, String lName) { // Constructor I'm using to try and increment the ID each time a Person object is created starting at 1001.
this.fName = fName;
this.lName = lName;
ID = ID + 1;
}
}
I am trying to create an address book whereby each contact has a first name, last name and a unique ID.
My question is how to I prevent a user from entering in duplicate contacts with the same first and last name? Should I implement some kind of check in the addContact method or right in main? How?
java object arraylist
|
show 1 more comment
switch(menuChoice) {
case 1:
System.out.println("Enter your contact's first name:n");
String fname = scnr.next();
System.out.println("Enter your contact's last name:n");
String lname = scnr.next();
Necronomicon.addContact(new Person(fname, lname));
break;
// main truncated here for readability
import java.util.ArrayList;
public class AddressBook {
ArrayList<Person> ArrayOfContacts= new ArrayList<Person>();
public void addContact(Person p) {
ArrayOfContacts.add(p);
/*
for(int i = 0; i < ArrayOfContacts.size(); i++) {
if(ArrayOfContacts.get(i).getID() != p.getID())
ArrayOfContacts.add(p);
else
System.out.println("Sorry this contact already exists.");
}
*/
}
}
public class Person {
private String fName = null;
private String lName = null;
private static int ID = 1000;
public Person(String fName, String lName) { // Constructor I'm using to try and increment the ID each time a Person object is created starting at 1001.
this.fName = fName;
this.lName = lName;
ID = ID + 1;
}
}
I am trying to create an address book whereby each contact has a first name, last name and a unique ID.
My question is how to I prevent a user from entering in duplicate contacts with the same first and last name? Should I implement some kind of check in the addContact method or right in main? How?
java object arraylist
Shouldn't you prevent the same id from being added? Normal address books have duplicate names
– cricket_007
Feb 27 '16 at 22:12
Good point. That is probably a better way to do it. Perhaps I could use the HashSet and just use the user ID's to prevent duplication.
– Nick M
Feb 27 '16 at 22:56
You can use aHashMap<Integer, Person>
– cricket_007
Feb 27 '16 at 22:58
I've not yet encountered HashMaps in my studies Cricket. I'm assuming instead of using an arrayList to store my person objects I could use the HashMap? Would I pass the unique IDs as the Integer parameter?
– Nick M
Feb 27 '16 at 23:54
For you case HashSet is the best option. By the way, there's the TreeSet collection which one doesn't accepts duplicate and order elements automatically. By the way, variables in Java should be camel case by convention. It should be arrayOfContacts.
– developer033
Feb 28 '16 at 1:16
|
show 1 more comment
switch(menuChoice) {
case 1:
System.out.println("Enter your contact's first name:n");
String fname = scnr.next();
System.out.println("Enter your contact's last name:n");
String lname = scnr.next();
Necronomicon.addContact(new Person(fname, lname));
break;
// main truncated here for readability
import java.util.ArrayList;
public class AddressBook {
ArrayList<Person> ArrayOfContacts= new ArrayList<Person>();
public void addContact(Person p) {
ArrayOfContacts.add(p);
/*
for(int i = 0; i < ArrayOfContacts.size(); i++) {
if(ArrayOfContacts.get(i).getID() != p.getID())
ArrayOfContacts.add(p);
else
System.out.println("Sorry this contact already exists.");
}
*/
}
}
public class Person {
private String fName = null;
private String lName = null;
private static int ID = 1000;
public Person(String fName, String lName) { // Constructor I'm using to try and increment the ID each time a Person object is created starting at 1001.
this.fName = fName;
this.lName = lName;
ID = ID + 1;
}
}
I am trying to create an address book whereby each contact has a first name, last name and a unique ID.
My question is how to I prevent a user from entering in duplicate contacts with the same first and last name? Should I implement some kind of check in the addContact method or right in main? How?
java object arraylist
switch(menuChoice) {
case 1:
System.out.println("Enter your contact's first name:n");
String fname = scnr.next();
System.out.println("Enter your contact's last name:n");
String lname = scnr.next();
Necronomicon.addContact(new Person(fname, lname));
break;
// main truncated here for readability
import java.util.ArrayList;
public class AddressBook {
ArrayList<Person> ArrayOfContacts= new ArrayList<Person>();
public void addContact(Person p) {
ArrayOfContacts.add(p);
/*
for(int i = 0; i < ArrayOfContacts.size(); i++) {
if(ArrayOfContacts.get(i).getID() != p.getID())
ArrayOfContacts.add(p);
else
System.out.println("Sorry this contact already exists.");
}
*/
}
}
public class Person {
private String fName = null;
private String lName = null;
private static int ID = 1000;
public Person(String fName, String lName) { // Constructor I'm using to try and increment the ID each time a Person object is created starting at 1001.
this.fName = fName;
this.lName = lName;
ID = ID + 1;
}
}
I am trying to create an address book whereby each contact has a first name, last name and a unique ID.
My question is how to I prevent a user from entering in duplicate contacts with the same first and last name? Should I implement some kind of check in the addContact method or right in main? How?
java object arraylist
java object arraylist
edited Feb 28 '16 at 1:35
cricket_007
82.4k1143111
82.4k1143111
asked Feb 27 '16 at 21:58
Nick MNick M
84
84
Shouldn't you prevent the same id from being added? Normal address books have duplicate names
– cricket_007
Feb 27 '16 at 22:12
Good point. That is probably a better way to do it. Perhaps I could use the HashSet and just use the user ID's to prevent duplication.
– Nick M
Feb 27 '16 at 22:56
You can use aHashMap<Integer, Person>
– cricket_007
Feb 27 '16 at 22:58
I've not yet encountered HashMaps in my studies Cricket. I'm assuming instead of using an arrayList to store my person objects I could use the HashMap? Would I pass the unique IDs as the Integer parameter?
– Nick M
Feb 27 '16 at 23:54
For you case HashSet is the best option. By the way, there's the TreeSet collection which one doesn't accepts duplicate and order elements automatically. By the way, variables in Java should be camel case by convention. It should be arrayOfContacts.
– developer033
Feb 28 '16 at 1:16
|
show 1 more comment
Shouldn't you prevent the same id from being added? Normal address books have duplicate names
– cricket_007
Feb 27 '16 at 22:12
Good point. That is probably a better way to do it. Perhaps I could use the HashSet and just use the user ID's to prevent duplication.
– Nick M
Feb 27 '16 at 22:56
You can use aHashMap<Integer, Person>
– cricket_007
Feb 27 '16 at 22:58
I've not yet encountered HashMaps in my studies Cricket. I'm assuming instead of using an arrayList to store my person objects I could use the HashMap? Would I pass the unique IDs as the Integer parameter?
– Nick M
Feb 27 '16 at 23:54
For you case HashSet is the best option. By the way, there's the TreeSet collection which one doesn't accepts duplicate and order elements automatically. By the way, variables in Java should be camel case by convention. It should be arrayOfContacts.
– developer033
Feb 28 '16 at 1:16
Shouldn't you prevent the same id from being added? Normal address books have duplicate names
– cricket_007
Feb 27 '16 at 22:12
Shouldn't you prevent the same id from being added? Normal address books have duplicate names
– cricket_007
Feb 27 '16 at 22:12
Good point. That is probably a better way to do it. Perhaps I could use the HashSet and just use the user ID's to prevent duplication.
– Nick M
Feb 27 '16 at 22:56
Good point. That is probably a better way to do it. Perhaps I could use the HashSet and just use the user ID's to prevent duplication.
– Nick M
Feb 27 '16 at 22:56
You can use a
HashMap<Integer, Person>
– cricket_007
Feb 27 '16 at 22:58
You can use a
HashMap<Integer, Person>
– cricket_007
Feb 27 '16 at 22:58
I've not yet encountered HashMaps in my studies Cricket. I'm assuming instead of using an arrayList to store my person objects I could use the HashMap? Would I pass the unique IDs as the Integer parameter?
– Nick M
Feb 27 '16 at 23:54
I've not yet encountered HashMaps in my studies Cricket. I'm assuming instead of using an arrayList to store my person objects I could use the HashMap? Would I pass the unique IDs as the Integer parameter?
– Nick M
Feb 27 '16 at 23:54
For you case HashSet is the best option. By the way, there's the TreeSet collection which one doesn't accepts duplicate and order elements automatically. By the way, variables in Java should be camel case by convention. It should be arrayOfContacts.
– developer033
Feb 28 '16 at 1:16
For you case HashSet is the best option. By the way, there's the TreeSet collection which one doesn't accepts duplicate and order elements automatically. By the way, variables in Java should be camel case by convention. It should be arrayOfContacts.
– developer033
Feb 28 '16 at 1:16
|
show 1 more comment
4 Answers
4
active
oldest
votes
Here is the code for keeping out duplicate ID's.
public void addContact(Person p) {
for(int i = 0; i < ArrayOfContacts.size(); i++) {
Person contact = ArrayOfContacts.get(i);
if(contact.getID() == p.getID()) {
System.out.println("Sorry this contact already exists.");
return; // the id exists, so we exit the method.
}
}
// Otherwise... you've checked all the elements, and have not found a duplicate
ArrayOfContacts.add(p);
}
If you would like to change this code to keep out duplicate names, then do something like this
public void addContact(Person p) {
String pName = p.getFname() + p.getLname();
for(int i = 0; i < ArrayOfContacts.size(); i++) {
Person contact = ArrayOfContacts.get(i);
String contactName = contact.getFname() + contact.getLname();
if(contactName.equals(pName)) {
System.out.println("Sorry this contact already exists.");
return; // the name exists, so we exit the method.
}
}
// Otherwise... you've checked all the elements, and have not found a duplicate
ArrayOfContacts.add(p);
}
Nice thank you. I'll play with this code a little bit. Check my edit, would the way I'm using work if I could figure out how to increment each user Id correctly? I have to assign a unique ID to each person object starting at 1000. I figured I'd just increment by one every time I create a new person object. Problem is, I'm not incrementing correctly.
– Nick M
Feb 28 '16 at 1:33
Each Person will have the same ID since you using astatic
variable. This is a "class variable", not an "instance" variable. If you would like an incrementing ID, you'll need aprivate int id;
and set it in your constructor tothis.id = ++ID
.
– cricket_007
Feb 28 '16 at 1:38
Tried that but it's just giving every person the same ID. Maybe the way I'm testing to see which ID each object is getting is wrong. Ugh.
– Nick M
Feb 28 '16 at 2:06
If you look at developer033's solution, he does what I was hinting at
– cricket_007
Feb 28 '16 at 2:13
@NickM See here for an example of the ids. repl.it/Bqz9/1
– cricket_007
Feb 28 '16 at 2:17
|
show 1 more comment
You could simply use HashSet and avoid any kind of loops to test it. HashSet is in charge of this function.
import java.util.Set;
import java.util.HashSet;
public class AddressBook {
Set<Person> listOfContacts = new HashSet<>();
public void addContact(Person p) {
if (!listOfContacts.add(p))
System.out.println("Sorry this contact already exists.");
}
}
To increment ID property you should have 2 properties, 1 static and another one, and increment it in constructor. Look:
public class Person {
private final int ID;
private static int id = 1000;
private String fName;
private String lName;
public Person(String fName, String lName) { // Constructor I'm using to try and increment the ID each time a Person object is created starting at 1001.
this.ID= ++id;
this.fName = fName;
this.lName = lName;
}
To make the HashSet not accept duplicate objects you should set which properties should not be duplicated in the class (Person in your case). Follows an example:
@Override
public int hashCode() {
int hash = 7;
hash = 61 * hash + Objects.hashCode(this.fName);
hash = 61 * hash + Objects.hashCode(this.lName);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass())
return false;
final Person other = (Person) obj;
if (!Objects.equals(this.fName, other.fName))
return false;
return Objects.equals(this.lName, other.lName);
}
}
By the way, you can generate equals
and hashCode
methods using your IDE (Eclipse, NetBeans, etc.)
EDIT
Since you aren't able to use HashSet, I will show a version with ArrayList. By the way, you have to use HashCode
and equals
as I said to make it work well
import java.util.List;
import java.util.ArrayList;
public class AddressBook {
List<Person> arrayOfContacts = new ArrayList<>();
public void addContact(Person p) {
if (listOfContacts.contains(p))
System.out.println("Sorry this contact already exists.");
else
arrayOfContacts.add(p);
}
}
Thanks developer. I got it to at least increment correctly now! I have been trying to avoid using the hash set stuff since we have not yet covered it in our class. It appears to make things a lot easier.
– Nick M
Feb 28 '16 at 2:21
@NickM you could have said this in his post, anyway, I updated my answer. Take a look. Mark as answer if that answered your question.
– developer033
Feb 28 '16 at 2:30
add a comment |
Use a HashSet. For every user's name, add it to the HashSet.
For example:
HashSet<String> namesUsed = new HashSet<String>();
if (namesUsed.contains(userName)) {
//do what you want here, if this is entered it means there is a duplicate
} else {
namesUsed.add(userName); //add it to the list of used names
}
I don't think there needs to be an if-else since adding the same name 'has no effect"
– cricket_007
Feb 27 '16 at 22:11
@cricket_007 Maybe he wants to display a message for user informing that the contact already exists. But I would do different (to prevent call 2 methods - contains and add), since the add method returns a Boolean, I would do: If (!nameUsed.add(userName) { then display msg. }, so ELSE is not required.
– developer033
Feb 28 '16 at 1:14
Yeah, that's what I was going for. I commented above that address books are allowed to have duplicate names, though
– cricket_007
Feb 28 '16 at 1:17
add a comment |
You should Override equals inside your Person class
public boolean equals(Object obj) {
if(fName.equals(obj.getfName()) && lName.equals(obj.getlName)) {
return true;
}
return false;
}
Then just call:
if(!(person1.equals(person2))) {
//not a duplicate
}
And of course substitute the variables/objects with whatever objects you want.
You also should add getters and setters for last and first name.
Hope this helps!
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f35675953%2fjava-address-book-how-to-prevent-duplicate-contacts-in-my-code%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
Here is the code for keeping out duplicate ID's.
public void addContact(Person p) {
for(int i = 0; i < ArrayOfContacts.size(); i++) {
Person contact = ArrayOfContacts.get(i);
if(contact.getID() == p.getID()) {
System.out.println("Sorry this contact already exists.");
return; // the id exists, so we exit the method.
}
}
// Otherwise... you've checked all the elements, and have not found a duplicate
ArrayOfContacts.add(p);
}
If you would like to change this code to keep out duplicate names, then do something like this
public void addContact(Person p) {
String pName = p.getFname() + p.getLname();
for(int i = 0; i < ArrayOfContacts.size(); i++) {
Person contact = ArrayOfContacts.get(i);
String contactName = contact.getFname() + contact.getLname();
if(contactName.equals(pName)) {
System.out.println("Sorry this contact already exists.");
return; // the name exists, so we exit the method.
}
}
// Otherwise... you've checked all the elements, and have not found a duplicate
ArrayOfContacts.add(p);
}
Nice thank you. I'll play with this code a little bit. Check my edit, would the way I'm using work if I could figure out how to increment each user Id correctly? I have to assign a unique ID to each person object starting at 1000. I figured I'd just increment by one every time I create a new person object. Problem is, I'm not incrementing correctly.
– Nick M
Feb 28 '16 at 1:33
Each Person will have the same ID since you using astatic
variable. This is a "class variable", not an "instance" variable. If you would like an incrementing ID, you'll need aprivate int id;
and set it in your constructor tothis.id = ++ID
.
– cricket_007
Feb 28 '16 at 1:38
Tried that but it's just giving every person the same ID. Maybe the way I'm testing to see which ID each object is getting is wrong. Ugh.
– Nick M
Feb 28 '16 at 2:06
If you look at developer033's solution, he does what I was hinting at
– cricket_007
Feb 28 '16 at 2:13
@NickM See here for an example of the ids. repl.it/Bqz9/1
– cricket_007
Feb 28 '16 at 2:17
|
show 1 more comment
Here is the code for keeping out duplicate ID's.
public void addContact(Person p) {
for(int i = 0; i < ArrayOfContacts.size(); i++) {
Person contact = ArrayOfContacts.get(i);
if(contact.getID() == p.getID()) {
System.out.println("Sorry this contact already exists.");
return; // the id exists, so we exit the method.
}
}
// Otherwise... you've checked all the elements, and have not found a duplicate
ArrayOfContacts.add(p);
}
If you would like to change this code to keep out duplicate names, then do something like this
public void addContact(Person p) {
String pName = p.getFname() + p.getLname();
for(int i = 0; i < ArrayOfContacts.size(); i++) {
Person contact = ArrayOfContacts.get(i);
String contactName = contact.getFname() + contact.getLname();
if(contactName.equals(pName)) {
System.out.println("Sorry this contact already exists.");
return; // the name exists, so we exit the method.
}
}
// Otherwise... you've checked all the elements, and have not found a duplicate
ArrayOfContacts.add(p);
}
Nice thank you. I'll play with this code a little bit. Check my edit, would the way I'm using work if I could figure out how to increment each user Id correctly? I have to assign a unique ID to each person object starting at 1000. I figured I'd just increment by one every time I create a new person object. Problem is, I'm not incrementing correctly.
– Nick M
Feb 28 '16 at 1:33
Each Person will have the same ID since you using astatic
variable. This is a "class variable", not an "instance" variable. If you would like an incrementing ID, you'll need aprivate int id;
and set it in your constructor tothis.id = ++ID
.
– cricket_007
Feb 28 '16 at 1:38
Tried that but it's just giving every person the same ID. Maybe the way I'm testing to see which ID each object is getting is wrong. Ugh.
– Nick M
Feb 28 '16 at 2:06
If you look at developer033's solution, he does what I was hinting at
– cricket_007
Feb 28 '16 at 2:13
@NickM See here for an example of the ids. repl.it/Bqz9/1
– cricket_007
Feb 28 '16 at 2:17
|
show 1 more comment
Here is the code for keeping out duplicate ID's.
public void addContact(Person p) {
for(int i = 0; i < ArrayOfContacts.size(); i++) {
Person contact = ArrayOfContacts.get(i);
if(contact.getID() == p.getID()) {
System.out.println("Sorry this contact already exists.");
return; // the id exists, so we exit the method.
}
}
// Otherwise... you've checked all the elements, and have not found a duplicate
ArrayOfContacts.add(p);
}
If you would like to change this code to keep out duplicate names, then do something like this
public void addContact(Person p) {
String pName = p.getFname() + p.getLname();
for(int i = 0; i < ArrayOfContacts.size(); i++) {
Person contact = ArrayOfContacts.get(i);
String contactName = contact.getFname() + contact.getLname();
if(contactName.equals(pName)) {
System.out.println("Sorry this contact already exists.");
return; // the name exists, so we exit the method.
}
}
// Otherwise... you've checked all the elements, and have not found a duplicate
ArrayOfContacts.add(p);
}
Here is the code for keeping out duplicate ID's.
public void addContact(Person p) {
for(int i = 0; i < ArrayOfContacts.size(); i++) {
Person contact = ArrayOfContacts.get(i);
if(contact.getID() == p.getID()) {
System.out.println("Sorry this contact already exists.");
return; // the id exists, so we exit the method.
}
}
// Otherwise... you've checked all the elements, and have not found a duplicate
ArrayOfContacts.add(p);
}
If you would like to change this code to keep out duplicate names, then do something like this
public void addContact(Person p) {
String pName = p.getFname() + p.getLname();
for(int i = 0; i < ArrayOfContacts.size(); i++) {
Person contact = ArrayOfContacts.get(i);
String contactName = contact.getFname() + contact.getLname();
if(contactName.equals(pName)) {
System.out.println("Sorry this contact already exists.");
return; // the name exists, so we exit the method.
}
}
// Otherwise... you've checked all the elements, and have not found a duplicate
ArrayOfContacts.add(p);
}
edited Feb 28 '16 at 1:39
answered Feb 28 '16 at 1:24
cricket_007cricket_007
82.4k1143111
82.4k1143111
Nice thank you. I'll play with this code a little bit. Check my edit, would the way I'm using work if I could figure out how to increment each user Id correctly? I have to assign a unique ID to each person object starting at 1000. I figured I'd just increment by one every time I create a new person object. Problem is, I'm not incrementing correctly.
– Nick M
Feb 28 '16 at 1:33
Each Person will have the same ID since you using astatic
variable. This is a "class variable", not an "instance" variable. If you would like an incrementing ID, you'll need aprivate int id;
and set it in your constructor tothis.id = ++ID
.
– cricket_007
Feb 28 '16 at 1:38
Tried that but it's just giving every person the same ID. Maybe the way I'm testing to see which ID each object is getting is wrong. Ugh.
– Nick M
Feb 28 '16 at 2:06
If you look at developer033's solution, he does what I was hinting at
– cricket_007
Feb 28 '16 at 2:13
@NickM See here for an example of the ids. repl.it/Bqz9/1
– cricket_007
Feb 28 '16 at 2:17
|
show 1 more comment
Nice thank you. I'll play with this code a little bit. Check my edit, would the way I'm using work if I could figure out how to increment each user Id correctly? I have to assign a unique ID to each person object starting at 1000. I figured I'd just increment by one every time I create a new person object. Problem is, I'm not incrementing correctly.
– Nick M
Feb 28 '16 at 1:33
Each Person will have the same ID since you using astatic
variable. This is a "class variable", not an "instance" variable. If you would like an incrementing ID, you'll need aprivate int id;
and set it in your constructor tothis.id = ++ID
.
– cricket_007
Feb 28 '16 at 1:38
Tried that but it's just giving every person the same ID. Maybe the way I'm testing to see which ID each object is getting is wrong. Ugh.
– Nick M
Feb 28 '16 at 2:06
If you look at developer033's solution, he does what I was hinting at
– cricket_007
Feb 28 '16 at 2:13
@NickM See here for an example of the ids. repl.it/Bqz9/1
– cricket_007
Feb 28 '16 at 2:17
Nice thank you. I'll play with this code a little bit. Check my edit, would the way I'm using work if I could figure out how to increment each user Id correctly? I have to assign a unique ID to each person object starting at 1000. I figured I'd just increment by one every time I create a new person object. Problem is, I'm not incrementing correctly.
– Nick M
Feb 28 '16 at 1:33
Nice thank you. I'll play with this code a little bit. Check my edit, would the way I'm using work if I could figure out how to increment each user Id correctly? I have to assign a unique ID to each person object starting at 1000. I figured I'd just increment by one every time I create a new person object. Problem is, I'm not incrementing correctly.
– Nick M
Feb 28 '16 at 1:33
Each Person will have the same ID since you using a
static
variable. This is a "class variable", not an "instance" variable. If you would like an incrementing ID, you'll need a private int id;
and set it in your constructor to this.id = ++ID
.– cricket_007
Feb 28 '16 at 1:38
Each Person will have the same ID since you using a
static
variable. This is a "class variable", not an "instance" variable. If you would like an incrementing ID, you'll need a private int id;
and set it in your constructor to this.id = ++ID
.– cricket_007
Feb 28 '16 at 1:38
Tried that but it's just giving every person the same ID. Maybe the way I'm testing to see which ID each object is getting is wrong. Ugh.
– Nick M
Feb 28 '16 at 2:06
Tried that but it's just giving every person the same ID. Maybe the way I'm testing to see which ID each object is getting is wrong. Ugh.
– Nick M
Feb 28 '16 at 2:06
If you look at developer033's solution, he does what I was hinting at
– cricket_007
Feb 28 '16 at 2:13
If you look at developer033's solution, he does what I was hinting at
– cricket_007
Feb 28 '16 at 2:13
@NickM See here for an example of the ids. repl.it/Bqz9/1
– cricket_007
Feb 28 '16 at 2:17
@NickM See here for an example of the ids. repl.it/Bqz9/1
– cricket_007
Feb 28 '16 at 2:17
|
show 1 more comment
You could simply use HashSet and avoid any kind of loops to test it. HashSet is in charge of this function.
import java.util.Set;
import java.util.HashSet;
public class AddressBook {
Set<Person> listOfContacts = new HashSet<>();
public void addContact(Person p) {
if (!listOfContacts.add(p))
System.out.println("Sorry this contact already exists.");
}
}
To increment ID property you should have 2 properties, 1 static and another one, and increment it in constructor. Look:
public class Person {
private final int ID;
private static int id = 1000;
private String fName;
private String lName;
public Person(String fName, String lName) { // Constructor I'm using to try and increment the ID each time a Person object is created starting at 1001.
this.ID= ++id;
this.fName = fName;
this.lName = lName;
}
To make the HashSet not accept duplicate objects you should set which properties should not be duplicated in the class (Person in your case). Follows an example:
@Override
public int hashCode() {
int hash = 7;
hash = 61 * hash + Objects.hashCode(this.fName);
hash = 61 * hash + Objects.hashCode(this.lName);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass())
return false;
final Person other = (Person) obj;
if (!Objects.equals(this.fName, other.fName))
return false;
return Objects.equals(this.lName, other.lName);
}
}
By the way, you can generate equals
and hashCode
methods using your IDE (Eclipse, NetBeans, etc.)
EDIT
Since you aren't able to use HashSet, I will show a version with ArrayList. By the way, you have to use HashCode
and equals
as I said to make it work well
import java.util.List;
import java.util.ArrayList;
public class AddressBook {
List<Person> arrayOfContacts = new ArrayList<>();
public void addContact(Person p) {
if (listOfContacts.contains(p))
System.out.println("Sorry this contact already exists.");
else
arrayOfContacts.add(p);
}
}
Thanks developer. I got it to at least increment correctly now! I have been trying to avoid using the hash set stuff since we have not yet covered it in our class. It appears to make things a lot easier.
– Nick M
Feb 28 '16 at 2:21
@NickM you could have said this in his post, anyway, I updated my answer. Take a look. Mark as answer if that answered your question.
– developer033
Feb 28 '16 at 2:30
add a comment |
You could simply use HashSet and avoid any kind of loops to test it. HashSet is in charge of this function.
import java.util.Set;
import java.util.HashSet;
public class AddressBook {
Set<Person> listOfContacts = new HashSet<>();
public void addContact(Person p) {
if (!listOfContacts.add(p))
System.out.println("Sorry this contact already exists.");
}
}
To increment ID property you should have 2 properties, 1 static and another one, and increment it in constructor. Look:
public class Person {
private final int ID;
private static int id = 1000;
private String fName;
private String lName;
public Person(String fName, String lName) { // Constructor I'm using to try and increment the ID each time a Person object is created starting at 1001.
this.ID= ++id;
this.fName = fName;
this.lName = lName;
}
To make the HashSet not accept duplicate objects you should set which properties should not be duplicated in the class (Person in your case). Follows an example:
@Override
public int hashCode() {
int hash = 7;
hash = 61 * hash + Objects.hashCode(this.fName);
hash = 61 * hash + Objects.hashCode(this.lName);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass())
return false;
final Person other = (Person) obj;
if (!Objects.equals(this.fName, other.fName))
return false;
return Objects.equals(this.lName, other.lName);
}
}
By the way, you can generate equals
and hashCode
methods using your IDE (Eclipse, NetBeans, etc.)
EDIT
Since you aren't able to use HashSet, I will show a version with ArrayList. By the way, you have to use HashCode
and equals
as I said to make it work well
import java.util.List;
import java.util.ArrayList;
public class AddressBook {
List<Person> arrayOfContacts = new ArrayList<>();
public void addContact(Person p) {
if (listOfContacts.contains(p))
System.out.println("Sorry this contact already exists.");
else
arrayOfContacts.add(p);
}
}
Thanks developer. I got it to at least increment correctly now! I have been trying to avoid using the hash set stuff since we have not yet covered it in our class. It appears to make things a lot easier.
– Nick M
Feb 28 '16 at 2:21
@NickM you could have said this in his post, anyway, I updated my answer. Take a look. Mark as answer if that answered your question.
– developer033
Feb 28 '16 at 2:30
add a comment |
You could simply use HashSet and avoid any kind of loops to test it. HashSet is in charge of this function.
import java.util.Set;
import java.util.HashSet;
public class AddressBook {
Set<Person> listOfContacts = new HashSet<>();
public void addContact(Person p) {
if (!listOfContacts.add(p))
System.out.println("Sorry this contact already exists.");
}
}
To increment ID property you should have 2 properties, 1 static and another one, and increment it in constructor. Look:
public class Person {
private final int ID;
private static int id = 1000;
private String fName;
private String lName;
public Person(String fName, String lName) { // Constructor I'm using to try and increment the ID each time a Person object is created starting at 1001.
this.ID= ++id;
this.fName = fName;
this.lName = lName;
}
To make the HashSet not accept duplicate objects you should set which properties should not be duplicated in the class (Person in your case). Follows an example:
@Override
public int hashCode() {
int hash = 7;
hash = 61 * hash + Objects.hashCode(this.fName);
hash = 61 * hash + Objects.hashCode(this.lName);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass())
return false;
final Person other = (Person) obj;
if (!Objects.equals(this.fName, other.fName))
return false;
return Objects.equals(this.lName, other.lName);
}
}
By the way, you can generate equals
and hashCode
methods using your IDE (Eclipse, NetBeans, etc.)
EDIT
Since you aren't able to use HashSet, I will show a version with ArrayList. By the way, you have to use HashCode
and equals
as I said to make it work well
import java.util.List;
import java.util.ArrayList;
public class AddressBook {
List<Person> arrayOfContacts = new ArrayList<>();
public void addContact(Person p) {
if (listOfContacts.contains(p))
System.out.println("Sorry this contact already exists.");
else
arrayOfContacts.add(p);
}
}
You could simply use HashSet and avoid any kind of loops to test it. HashSet is in charge of this function.
import java.util.Set;
import java.util.HashSet;
public class AddressBook {
Set<Person> listOfContacts = new HashSet<>();
public void addContact(Person p) {
if (!listOfContacts.add(p))
System.out.println("Sorry this contact already exists.");
}
}
To increment ID property you should have 2 properties, 1 static and another one, and increment it in constructor. Look:
public class Person {
private final int ID;
private static int id = 1000;
private String fName;
private String lName;
public Person(String fName, String lName) { // Constructor I'm using to try and increment the ID each time a Person object is created starting at 1001.
this.ID= ++id;
this.fName = fName;
this.lName = lName;
}
To make the HashSet not accept duplicate objects you should set which properties should not be duplicated in the class (Person in your case). Follows an example:
@Override
public int hashCode() {
int hash = 7;
hash = 61 * hash + Objects.hashCode(this.fName);
hash = 61 * hash + Objects.hashCode(this.lName);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass())
return false;
final Person other = (Person) obj;
if (!Objects.equals(this.fName, other.fName))
return false;
return Objects.equals(this.lName, other.lName);
}
}
By the way, you can generate equals
and hashCode
methods using your IDE (Eclipse, NetBeans, etc.)
EDIT
Since you aren't able to use HashSet, I will show a version with ArrayList. By the way, you have to use HashCode
and equals
as I said to make it work well
import java.util.List;
import java.util.ArrayList;
public class AddressBook {
List<Person> arrayOfContacts = new ArrayList<>();
public void addContact(Person p) {
if (listOfContacts.contains(p))
System.out.println("Sorry this contact already exists.");
else
arrayOfContacts.add(p);
}
}
edited Feb 28 '16 at 2:29
answered Feb 28 '16 at 1:41
developer033developer033
14k53767
14k53767
Thanks developer. I got it to at least increment correctly now! I have been trying to avoid using the hash set stuff since we have not yet covered it in our class. It appears to make things a lot easier.
– Nick M
Feb 28 '16 at 2:21
@NickM you could have said this in his post, anyway, I updated my answer. Take a look. Mark as answer if that answered your question.
– developer033
Feb 28 '16 at 2:30
add a comment |
Thanks developer. I got it to at least increment correctly now! I have been trying to avoid using the hash set stuff since we have not yet covered it in our class. It appears to make things a lot easier.
– Nick M
Feb 28 '16 at 2:21
@NickM you could have said this in his post, anyway, I updated my answer. Take a look. Mark as answer if that answered your question.
– developer033
Feb 28 '16 at 2:30
Thanks developer. I got it to at least increment correctly now! I have been trying to avoid using the hash set stuff since we have not yet covered it in our class. It appears to make things a lot easier.
– Nick M
Feb 28 '16 at 2:21
Thanks developer. I got it to at least increment correctly now! I have been trying to avoid using the hash set stuff since we have not yet covered it in our class. It appears to make things a lot easier.
– Nick M
Feb 28 '16 at 2:21
@NickM you could have said this in his post, anyway, I updated my answer. Take a look. Mark as answer if that answered your question.
– developer033
Feb 28 '16 at 2:30
@NickM you could have said this in his post, anyway, I updated my answer. Take a look. Mark as answer if that answered your question.
– developer033
Feb 28 '16 at 2:30
add a comment |
Use a HashSet. For every user's name, add it to the HashSet.
For example:
HashSet<String> namesUsed = new HashSet<String>();
if (namesUsed.contains(userName)) {
//do what you want here, if this is entered it means there is a duplicate
} else {
namesUsed.add(userName); //add it to the list of used names
}
I don't think there needs to be an if-else since adding the same name 'has no effect"
– cricket_007
Feb 27 '16 at 22:11
@cricket_007 Maybe he wants to display a message for user informing that the contact already exists. But I would do different (to prevent call 2 methods - contains and add), since the add method returns a Boolean, I would do: If (!nameUsed.add(userName) { then display msg. }, so ELSE is not required.
– developer033
Feb 28 '16 at 1:14
Yeah, that's what I was going for. I commented above that address books are allowed to have duplicate names, though
– cricket_007
Feb 28 '16 at 1:17
add a comment |
Use a HashSet. For every user's name, add it to the HashSet.
For example:
HashSet<String> namesUsed = new HashSet<String>();
if (namesUsed.contains(userName)) {
//do what you want here, if this is entered it means there is a duplicate
} else {
namesUsed.add(userName); //add it to the list of used names
}
I don't think there needs to be an if-else since adding the same name 'has no effect"
– cricket_007
Feb 27 '16 at 22:11
@cricket_007 Maybe he wants to display a message for user informing that the contact already exists. But I would do different (to prevent call 2 methods - contains and add), since the add method returns a Boolean, I would do: If (!nameUsed.add(userName) { then display msg. }, so ELSE is not required.
– developer033
Feb 28 '16 at 1:14
Yeah, that's what I was going for. I commented above that address books are allowed to have duplicate names, though
– cricket_007
Feb 28 '16 at 1:17
add a comment |
Use a HashSet. For every user's name, add it to the HashSet.
For example:
HashSet<String> namesUsed = new HashSet<String>();
if (namesUsed.contains(userName)) {
//do what you want here, if this is entered it means there is a duplicate
} else {
namesUsed.add(userName); //add it to the list of used names
}
Use a HashSet. For every user's name, add it to the HashSet.
For example:
HashSet<String> namesUsed = new HashSet<String>();
if (namesUsed.contains(userName)) {
//do what you want here, if this is entered it means there is a duplicate
} else {
namesUsed.add(userName); //add it to the list of used names
}
answered Feb 27 '16 at 22:08
questioner and answererquestioner and answerer
661314
661314
I don't think there needs to be an if-else since adding the same name 'has no effect"
– cricket_007
Feb 27 '16 at 22:11
@cricket_007 Maybe he wants to display a message for user informing that the contact already exists. But I would do different (to prevent call 2 methods - contains and add), since the add method returns a Boolean, I would do: If (!nameUsed.add(userName) { then display msg. }, so ELSE is not required.
– developer033
Feb 28 '16 at 1:14
Yeah, that's what I was going for. I commented above that address books are allowed to have duplicate names, though
– cricket_007
Feb 28 '16 at 1:17
add a comment |
I don't think there needs to be an if-else since adding the same name 'has no effect"
– cricket_007
Feb 27 '16 at 22:11
@cricket_007 Maybe he wants to display a message for user informing that the contact already exists. But I would do different (to prevent call 2 methods - contains and add), since the add method returns a Boolean, I would do: If (!nameUsed.add(userName) { then display msg. }, so ELSE is not required.
– developer033
Feb 28 '16 at 1:14
Yeah, that's what I was going for. I commented above that address books are allowed to have duplicate names, though
– cricket_007
Feb 28 '16 at 1:17
I don't think there needs to be an if-else since adding the same name 'has no effect"
– cricket_007
Feb 27 '16 at 22:11
I don't think there needs to be an if-else since adding the same name 'has no effect"
– cricket_007
Feb 27 '16 at 22:11
@cricket_007 Maybe he wants to display a message for user informing that the contact already exists. But I would do different (to prevent call 2 methods - contains and add), since the add method returns a Boolean, I would do: If (!nameUsed.add(userName) { then display msg. }, so ELSE is not required.
– developer033
Feb 28 '16 at 1:14
@cricket_007 Maybe he wants to display a message for user informing that the contact already exists. But I would do different (to prevent call 2 methods - contains and add), since the add method returns a Boolean, I would do: If (!nameUsed.add(userName) { then display msg. }, so ELSE is not required.
– developer033
Feb 28 '16 at 1:14
Yeah, that's what I was going for. I commented above that address books are allowed to have duplicate names, though
– cricket_007
Feb 28 '16 at 1:17
Yeah, that's what I was going for. I commented above that address books are allowed to have duplicate names, though
– cricket_007
Feb 28 '16 at 1:17
add a comment |
You should Override equals inside your Person class
public boolean equals(Object obj) {
if(fName.equals(obj.getfName()) && lName.equals(obj.getlName)) {
return true;
}
return false;
}
Then just call:
if(!(person1.equals(person2))) {
//not a duplicate
}
And of course substitute the variables/objects with whatever objects you want.
You also should add getters and setters for last and first name.
Hope this helps!
add a comment |
You should Override equals inside your Person class
public boolean equals(Object obj) {
if(fName.equals(obj.getfName()) && lName.equals(obj.getlName)) {
return true;
}
return false;
}
Then just call:
if(!(person1.equals(person2))) {
//not a duplicate
}
And of course substitute the variables/objects with whatever objects you want.
You also should add getters and setters for last and first name.
Hope this helps!
add a comment |
You should Override equals inside your Person class
public boolean equals(Object obj) {
if(fName.equals(obj.getfName()) && lName.equals(obj.getlName)) {
return true;
}
return false;
}
Then just call:
if(!(person1.equals(person2))) {
//not a duplicate
}
And of course substitute the variables/objects with whatever objects you want.
You also should add getters and setters for last and first name.
Hope this helps!
You should Override equals inside your Person class
public boolean equals(Object obj) {
if(fName.equals(obj.getfName()) && lName.equals(obj.getlName)) {
return true;
}
return false;
}
Then just call:
if(!(person1.equals(person2))) {
//not a duplicate
}
And of course substitute the variables/objects with whatever objects you want.
You also should add getters and setters for last and first name.
Hope this helps!
answered Feb 28 '16 at 1:45
Gregory SaldanhaGregory Saldanha
911211
911211
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f35675953%2fjava-address-book-how-to-prevent-duplicate-contacts-in-my-code%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
Shouldn't you prevent the same id from being added? Normal address books have duplicate names
– cricket_007
Feb 27 '16 at 22:12
Good point. That is probably a better way to do it. Perhaps I could use the HashSet and just use the user ID's to prevent duplication.
– Nick M
Feb 27 '16 at 22:56
You can use a
HashMap<Integer, Person>
– cricket_007
Feb 27 '16 at 22:58
I've not yet encountered HashMaps in my studies Cricket. I'm assuming instead of using an arrayList to store my person objects I could use the HashMap? Would I pass the unique IDs as the Integer parameter?
– Nick M
Feb 27 '16 at 23:54
For you case HashSet is the best option. By the way, there's the TreeSet collection which one doesn't accepts duplicate and order elements automatically. By the way, variables in Java should be camel case by convention. It should be arrayOfContacts.
– developer033
Feb 28 '16 at 1:16