Checking a ArrayList of a class for duplicates - java

I have an ArrayList of a class that holds information, and I want to add to objects to this list. I want to check to see if that list already contains a number before adding it to a list.
Normally if it were just a list of strings I would just do something like this
if(!list.contains("this string")){
list.add("this string");
}
but since this is a class, it has more than one variable per index.
An example of the class world be this:
private class From{
private long threadID;
private long date;
private String address;
private String body;
private int type;
private long id;
#Override
public boolean equals(Object obj){
if(obj != null){
if(getClass() != obj.getClass()){
return false;
}else{
final From from = (From)obj;
if((this.address != null) ? (from.address != null) : !this.address.equals(from.address)){
return false;
}
}
}else{
return false;
}
return true;
}
}
I want to see if there is already an entry with the same number, so am I going to have to manually loop through each index and check, or is there an easier way of doing what I want to do?
EDIT:
how i call it
HashSet<From> addresses = new HashSet<From>();
From f = new From();
f.setAddress(messages.getString(3));
f.setBody(messages.getString(0));
f.setDate(messages.getLong(2));
f.setThreadId(messages.getLong(1));
f.setType(1);
if(!addresses.contains(f.address)){
addresses.add(f);
}

Use a Set instead of a List. Sets dont allow duplicates
http://docs.oracle.com/javase/6/docs/api/java/util/HashSet.html
You will also need to override equals in your class so the Set knows if two objects are equal
Example of overriding equals can be found here: How to override equals method in java

You have to override equals(Object o) for this. This is the place where you need to define the logic that would define the equality between two objects.
It is good practice to override hashCode() as well. Read more in the Javadocs for Object.

Another way would be to override equals() for Info object such that two Info objects are equal if they both have the same number. before adding the element into the list just do the equals() test .

You can still use the contains method; A List uses the equals method to determine if the item exists in the list. But you must override equals in your Info object.

Related

Comparing Objects saved in ArrayList using "Boolean equals()"

I've a Class called Products. This class has a name and a price.
I can create a product the following way:
Product book = new Product();
book.setName("book");
book.setPrice(3);
After that I'm supposed check if this product already exists in the ArrayList I'm supposed to save it to and if it doesn't, then I just put it there. I'm supposed to do this using the following:
public boolean equals(Object obj){
}
The problem is, how am I supposed to do it, if the ArrayList I'm supposed to save the product in, is created and initialised in the public static void main while this boolean is created before the ArrayList even exists?
Should I just make the Class itself an ArrayList, like so?
public class ArrayList<Product>{
}
Don't worry about it's existence. Since you are overiding equals method in your Product class, You can try doing this below
if(yourArayList.contains(book)){
// it existed in the list
}else{
yourArayList.add(book);
}
When you call the contains method it internally calls the equals method of Product method vs the object being passed to it.
This boolean is not created before your ArrayList exists.
You need to overwrite the equals() method of Product like this:
#Override
public boolean equals(Object obj) {
if(obj == this) return true; // Both objects have the same reference -> the objects are equal
if((obj == null) || (obj.getClass() != this.getClass())) return false; // Classes are different -> objects are different
Product p = (Product) obj; // Cast obj into Product
if( (this.getPrice() == p.getPrice()) && (this.getName().equals(p.getName())) ) return true; // Price and name are the same -> both products are the same
return false; // At this point the two objects can't be equal
}
This is how you create an ArrayList:
ArrayList<Product> products = new ArrayList<Product>();
And this is how you add a Product when it doesn't exist in the list:
if(!products.contains(yourProduct)){ // Checks if yourProduct is not contained in products
products.add(yourProduct); // adds yourProduct to products
}
this boolean is created before the ArrayList even exists?
You misunderstood the way equals works. It does not "create" a boolean until you call it with some object as an argument, and it returns a boolean based on the attributes of the object that you pass.
When you define your equals method you provide code to decide equality, but you are not deciding anything at that moment:
#Override
public boolean equals(Object obj){
if (obj == this) return true
if (!(obj instanceof Product)) return false;
Product other = (Product)obj;
if (!other.getName().equals(getName())) return false;
if (!other.getPrice() == getPrice()) return false;
return true;
}
#Override
public int hashCode() {
return 31*getName().hashCode() + getPrice();
}
Now you can use equals to deicide if a list has your Product in one of two ways:
Use contains - this method calls equals to check containment, or
Iterate all objects, and call equals manually.
You don't need to create your own ArrayList class.
If you implement you equals right, it will be called to check if you have it in the list when you execute myList.contains(book)
Actually there is a structure that will let you skip performing the check in your code. You can use the java.util.HashSet. It ensures that no duplicates can be added. In addition it returns the boolean value saying if the element was added. E.g.
Set<Product> mySet = new HashSet<>();
boolean added = mySet.add(book);
Please don't forget the easy to follow rule - when defining the equals, define the hashCode too. If you use an IDE, you can generate them both easily.

indexOf() for ArrayList of user defined objects not working

I am not getting the right answer when I try to use indexOf() of an ArrayList made up of user defined objects. Here is the code that creates one of the objects:
State kansas = new State("KS", 5570.81, 2000)
So, the name of the object is "kansas"
Here is the code that creates the ArrayList and adds the object:
ArrayList<State> allStates = new ArrayList<State>();
allStates.add(kansas);
And here is the code that I try to use to find the index of this object:
System.out.println(allStates.indexOf(kansas));
This is the point at which my compiler (Eclipse) throws me a red X indicating that there is a problem with my code and the problem is that it does not recognize 'kansas'. So I tried this:
String s = "kansas";
System.out.println(allStates.indexOf(s));
and it will run but the result is -1.
I am calling a method from a different class to create the ArrayList as opposed to creating it in the same class as my main method but I'm new enough to coding that I"m not sure if that is where I am going wrong. However, in order for the program that I am writing to work, I need to have data about each of the State objects stored so that I can access it from the main method.
Any advice?
*This is my first time posting a questions and I wasn't sure how much detail to go into so if I'm missing relevant information please let me know :)
method indexOf uses equlas() method to compare objects.
That why you have to override equals method in your custom class (if you planning use class in Map override hashCode method as well).
most IDE can generate these methods (equals and hashCode).
here simple example.
public class State {
private String stateCode;
public State(String stateCode /* other parameters*/) {
this.stateCode = stateCode;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
State state = (State) o;
return stateCode.equals(state.stateCode);
}
#Override
public int hashCode() {
return stateCode.hashCode();
}
}
This is because, String is not your custom object State type. Your array list is a list of all 'State' types, which is why this -
String s = "kansas";
System.out.println(allStates.indexOf(s));
won't work.
What you can do is have a convenience method that iterates through the list and returns the index.
private int getIndexOfState(String stateName) {
for(State stateObject : allStates) {
if(stateObject.getName().equals(stateName))
return allStates.indexOf(stateObject);
}
return -1;
}
Now you can reuse this method to find index of any state name you pass, and whenever the method returns -1, it means the stateName(state) was not found in the list of states.You can pass in 'Kansas' or 'California' or anything as the parameter to the method.
In your method call you say
System.out.println(getIndexOfState("Kansas"));
System.out.println(getIndexOfState("Chicago"));
The return value is -1 because there is no String "kansas" in allStates, and ArrayList#indexOf returns -1 if the element is not present in the list. If you try to add s to allStates, the compiler won't even let you, because State is not a String.
I don't know why you instantiated a String with the value "kansas", but if you need to refer to the State from its name (maybe the name comes from a Scanner input), you will need a Map<String, State>, such as:
Map<String, State> map = new HashMap<>();
map.put("kansas", kansas) // a String and the object named kansas
Then, you can do:
System.out.println(allStates.indexOf(map.get("kansas")))
//or
String s = "kansas";
System.out.println(allStates.indexOf(map.get(s)))

JUnit comparing two Lists of entities

I have:
List<SlaveEntityDTO> result = Jsoner.JsonToSlaveEntityDTO(json);
List<SlaveEntityDTO> result1 = entitiesDTOList;
The result and result1 has the same values for their fields:
When I run Assert.assertEquals(result, result1); I am getting the following message:
java.lang.AssertionError:
Expected :[core.dto.SlaveEntityDTO#6be46e8f, core.dto.SlaveEntityDTO#3567135c]
Actual :[core.dto.SlaveEntityDTO#327471b5, core.dto.SlaveEntityDTO#4157f54e]
So how can I compare the values of the fields inside result and result1, instead of comparing if an object is that object?
The SlaveEntityDTO is like this:
public class SlaveEntityDTO extends BaseEntityDTO<SlaveEntity> {
private String ip;
private String macAddress;
private String status;
private List<PositionEntity> positions;
#Override
public SlaveEntity convertToEntity() {
return new ModelMapper().map(this, SlaveEntity.class);
}
}
And the BaseEntityDTO is like this:
public abstract class BaseEntityDTO<T> implements Serializable{
private long id;
public abstract T convertToEntity();
}
Your test looks fine. The List interface defines the behavior of its equals, and your debugger shows that ArrayList is being used. ArrayList is a good guy, so we can assume that its implementation of equals is legit.
Thus, we can conclude that your SlaveEntityDTO class either does not override Object#equals(Object) or that it does so in a way that you aren't accounting for (which possibly means that it is implementing it incorrectly).
You can fix this by Overriding equals in BaseEntityDTO. This will give basic behavior of equals to every subclass.
#Override
public boolean equals(Object o) {
if (this == o) return true; // literally the same object.
if (o == null || getClass() != o.getClass()) return false; // Not correct type.
BaseEntityDTO that = (BaseEntityDTO) o;
return this.id == null ? that.id == null : this.id.equals(that.id);
}
And don't forget: hashCode() MUST match the implementation of equals!
#Override
public int hashCode() {
return id == null ? 0 : id.hashCode();
}
When I run Assert.assertEquals(result, result1); I am getting the
following message:
java.lang.AssertionError: Expected
:[core.dto.SlaveEntityDTO#6be46e8f, core.dto.SlaveEntityDTO#3567135c]
Actual :[core.dto.SlaveEntityDTO#327471b5,
core.dto.SlaveEntityDTO#4157f54e]
As you said, you are getting the error because you are comparing the objects and not the content of the two objects.
One way of doing it would be to convert both the JSON objects to Strings and then compare the two Strings but remember that order in JSON is not fixed and it might happen that your result object has the elements in order {2, 1, 3} but the source object has it in the order {1, 2, 3}.
I think you should try creating Sets out of your source elements and result elements and then compare both the Sets based on their sizes and also elements in it to assert whether the two objects are equal or not.
You can read this post here to know more about JSON comparison:

Detect if ArrayList contains multiple instance of the same object

I tried to detect if an ArrayList contains the same coppies of an object with no success. Here is my code;
public class Foo{
int id;
int name;
#Override
public boolean equals(Object o){
Foo f = (Foo)o;
return f.id==this.id;
}
}
//in another class
ArrayList<Foo> foos;
...
boolean ifFoosListContainsMultipleFoo(Foo f){
return foos.indexOf(f)!=foos.lastIndexOf(f);
}
//but this method always returns `false` even the `foos` list
//contains multiple object with the same `id`;
So, what am I doing wrong and is there a more optimal way of doing this?
Thanks in advance.
EDIT: I saw that I need to override hash method of the Foo class, then why equals function is not enough;
EDIT 2: Sorry for wasting your time but it was my mistake. There is no problem with my code, I used ifFoosListContainsMultipleFoo as !ifFoosListContainsMultipleFoo so this was result of false response.
Apologize me.
Your code should work as it is, except in the case where f is not present in the list at all..
So you can do something like,
boolean ifFoosListContainsMultipleFoo(Foo f){
return (foos.indexOf(f) != -1) && (foos.indexOf(f)!=foos.lastIndexOf(f));
}
You can use a HashSet<Foo> to do this. You should override hashCode as well because HashSet uses hashes internally.
Set<Foo> set = new HashSet<Foo>(foos);
// check for duplicates
set.size() == foos.size();
You can also use the set manually which should let you retain the duplicates and can let you end the check sooner (instead of adding everything):
Set<Foo> set = new HashSet<Foo>();
// check for duplicates
for (Foo foo : foos){
if (!set.contains(foo)){
set.add(foo);
} else {
// do something with foo, which is a duplicate.
// possibly end check for duplicates or store in a list
}
}

Java HashSet contains Object

I made my own class with an overridden equals method which just checks, if the names (attributes in the class) are equal. Now I store some instances of that class in a HashSet so that there are no instances with the same names in the HashSet.
My Question: How is it possible to check if the HashSet contains such an object. .contains() wont work in that case, because it works with the .equals() method. I want to check if it is really the same object.
edit:
package testprogram;
import java.util.HashSet;
import java.util.Set;
public class Example {
private static final Set<Example> set = new HashSet<Example>();
private final String name;
private int example;
public Example(String name, int example) {
this.name = name;
this.example = example;
set.add(this);
}
public boolean isThisInList() {
return set.contains(this);
//will return true if this is just equal to any instance in the list
//but it should not
//it should return true if the object is really in the list
}
public boolean remove() {
return set.remove(this);
}
//Override equals and hashCode
}
Sorry, my english skills are not very well. Please feel free to ask again if you don't understand what I mean.
In your situation, the only way to tell if a particular instance of an object is contained in the HashSet, is to iterate the contents of the HashSet, and compare the object identities ( using the == operator instead of the equals() method).
Something like:
boolean isObjectInSet(Object object, Set<? extends Object> set) {
boolean result = false;
for(Object o : set) {
if(o == object) {
result = true;
break;
}
}
return result;
}
The way to check if objects are the same object is by comparing them with == to see that the object references are equal.
Kind Greetings,
Frank
You will have to override the hashCode method also.
try this..
Considering only one property 'name' of your Objects to maintain uniqueness.
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (name == null ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
User other = (User) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
I made my own class with an overridden equals method which just checks, if the names (attributes in the class) are equal.
This breaks the contract of .equals, and you must never do it no matter how convenient it seems.
Instead, if you want to index and look up elements by a certain attribute such as the name, use a HashMap<Name, YourType> to find them. Alternatively, use a TreeSet and pass it a Comparator that compares the name only. You can then remove the incorrect equals method.
There are then three ways if you want to find objects by reference equality:
Your objects have no inherent or useful notion of equality.
Don't implement equals. Leave it to its default. You can then use a HashSet to look for reference equality, and a HashMap or TreeSet to index them by any specific attributes.
Your objects do have a useful, universal notion of equality, but you want to find equivalent instances efficiently anyways.
This is almost never the case. However, you can use e.g. an Apache IdentityMap.
You don't care about efficiency.
Use a for loop and == every element.
HashSet contains uses the equals method to determine if the object is contained - and duplicates are not kept within the HashSet.
Assuming your equals and hashcode are only using a name field...
HashSet<MyObject> objectSet = new HashSet<MyObject>();
MyObject name1Object = new MyObject("name1");
objectSet.add(new MyObject("name1"));
objectSet.add(name1Object);
objectSet.add(new MyObject("name2"));
//HashSet now contains 2 objects, name1Object and the new name2 object
//HashSets do not hold duplicate objects (name1Object and the new object with name1 would be considered duplicates)
objectSet.contains(new MyObject("name1")) // returns true
objectSet.contains(name1Object) // returns true
objectSet.contains(new MyObject("name2")) // returns true
objectSet.contains(new MyObject("name3")) // returns false
If you wanted to check if the object in the HashSet is the exact object you are comparing you would have to pull it out and compare it directly using ==
for (MyObject o : objectSet)
{
if (o == name1Object)
{
return true;
}
}
If you do this alot for specific objects it might be easier to use a HashMap so you don't have to iterate through the list to grab a specific named Object. May be worth looking into for you because then you could do something like this:
(objectMap.get("name") == myNameObject) // with a HashMap<String, MyNameObject> where "name" is the key string.

Categories

Resources