Remove Element in ArrayList in loop - java

I need help. I tried to remove an element from an ArrayList.
I have two lists. One list from a file, the second list from the database.
I need to find the same elements to later remove them from the original list, and thus have a list with differences.
List<BinInternacionalMarcaDEL> listDiff = new ArrayList<BinInternacionalMarcaDEL>();
ListOriginal= binInternacionalRepositoryDEL.findAllByBin();
public List<BinInternacionalMarcaDEL> Differences(List<BinInternacionalMarcaDEL> listA,
List<BinInternacionalMarcaDEL> listB) {
try {
for(BinInternacionalMarcaDEL elementA: listaA){
for(BinInternacionalMarcaDEL elementB: listaB) {
if(elementA.getNumRangoini().compareTo(elementB.getNumRangoini()) == 0 ){
listDiff.add(elementA);
}
}
}
ListOriginal.removeAll(listDiff);
} catch (Exception e) {
LOGGER.error(e.toString());
}
but this doesn't work.

just you can do one thing
listA.retainAll(listB);
here now listA contains only similar elements in both ListA and ListB.
Example:
List<String> listA = new ArrayList<>(Arrays.asList("12","13","15","2","5")) ;
List<String> listB = new ArrayList<> (Arrays.asList("2","12","48","49","55"));
listA .retainAll(listB );
System.out.println(listA ); //[12, 2]

Java list remove and contains methods are implemented using equality of objects. This logic is implemented in hashCode and equal method in your class and all classes in Java inherit this attribute from the Object class.(to be honest ArrayList doesn't use hashCode in implementing remove and contains metheds but in java contract you should implement these two methods together). here when you are adding element to listDiff you are defining your own equality which is based on equality of attribute numRangoini(using compateTo method) and when you request the list class to remove them from list(with removeAll method). removeAll remove them based on the equality of that two object. Since you haven't defined this logic in your own class.
this behaviour is inherited from object class which is based on strict equality. by default two object are equal if they reference the same object.
Solution: define the logic for equality in your own class in equal method. This method should return true if two object has the same attribute value numRangoini. don't forget to define hashCode as well. and here is the rule if two objects are equal they should return the same hashCode.
here is a simple implementation
#Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null || obj.getClass()!= this.getClass())
return false;
BinInternacionalMarcaDEL binInternacionalMarcaDEL = (BinInternacionalMarcaDEL)obj;
return (national.getNumRangoini().compareTo(this.getNumRangoini()) == 0);
}
#Override
public int hashCode() {
return this.getNumRangoini().intValue();
}

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.

How do I compare two lists?

CompareList removedList = new CompareList();
CompareList addedList = new CompareList();
This is how I'm adding elements inside
addedList.add(new Objec("Var_a", "1"));
and class Objec has two strings.
How can I compare that? I can't use contains like I could with ArrayList of Strings?
In CompareList I have
public boolean equals(CompareList l) {
if (l.containsAll(this)) {
if (this.containsAll(l)) {
return true;
}
}
return false;
}
and in Objec
public Objec(String n, String s) {
this.name=n;
this.surname=s;
}
public String toString() {
return " Name: " + name + ", Surname: " + surname;
}
I see that many people are confused with my question. So what I want?
List 1:
Samy Joe
Emma Than
Julia Rob
List 2:
Samy Joe
Emma Than
Anna Sky
Removed Julia Rob and added Anna Sky. But I don't know how to do it when my lists contains of object that have two strings?
This piece of code compares if the lists are equal, that is, contains the same elements.
static boolean same(Collection<?> a, Collection<?> b) {
if (a.size() != b.size()) {
return false;
}
List<?> c = new ArrayList<>(a);
c.removeAll(b);
return c.isEmpty();
}
If the sizes are not equal, then the lists are never equal.
Else, if the sizes are equal, then we know that both lists contain one or more elements that are not present in the other list. So we make a new list from one of the lists (list a in my case), and then we remove the elements of b.
You don't need to use your own class CompareList, instead you could just use an ArrayList or something.
In order to compare your Objec to another one, you'll need to implement equals(Object) and hashCode() correctly.
If you want to know which elements are not contained in the other list, then you can use this:
static HashMap<Collection<?>, Collection<?>> disjoints(Collection<?> a, Collection<?> b) {
List<?> aa = new ArrayList<>(a);
aa.removeAll(b);
List<?> bb = new ArrayList<>(b);
bb.removeAll(a);
HashMap<Collection<?>, Collection<?>> map = new HashMap<>();
map.put(a, aa);
map.put(b, bb);
return map;
}
It returns a map with as keys the two collections and as values the elements of the collection specified by the key, which are not contained in the other collection. For example, if you want to know the elements of a not present in b, then call disjoints(a, b).get(a).
Note: I call the lists collections, because they are. In Java, a List is a subtype of Collection.
You need to override the equals method in your custom object like this:
public class MyObject {
private String name;
private String surname;
#Override
public boolean equals(MyObject myObject) {
// assert that name and surename can not be null or check for this
if (!this.name.equals(myObject.name)) {
return false;
}
if (!this.surname.equals(myObject.surname)) {
return false;
}
return true;
}
}
The contains-Method of a list will be use the equals method to check the equality of your objects.
But the link that #Prakash has posted is the better way do do that. I think no one understand what your attention is to do with yout CompareList and why you use a custom one ;)
EDIT:
Sorry, had mistake in the Signature.
#Override
public boolean equals(Object obj) {
if (!(obj instanceof MyObject) {
return false;
}
// else cast and use code above
}
You're question: "How can I compare that?"
The first thing to keep in mind is that you can compare in 2 ways.
so think about that first.
Equality:
When comparing for equality
use equals() and while you're at it implement hashCode().
Comparing / sorting:
When are 2 objects considered lower then, same, or higher then the other?
implement "Comparable" interface and override compareTo.
You're post contains the equals() so lets say that is what you want to do.
If you want to use containsAll(), keep in mind that it uses equals from the class the list contains to figure out to return true/false. So you should probably:
add equals() to your "Objec" class.

Can I use Set collection to eliminate duplicate by two different equals?

I have a project in Java. First I need to create a collection with no duplicates in the name of object & its number, so I use the Set collection and this equals method:
public boolean equals(Object obj) {
Course<?> c=(Course<?>)obj;
return (c.number==number&& c.Name.equals(Name));
}
next ..i need to create collection of the same object but now i need to insure that only his name is not duplicate. so its a problem because i cant use two diffrents methods of equals
what can i do??
I'd use a TreeSet instead and specifying the comparator to use for that specific set instead of overriding equals.
https://docs.oracle.com/javase/8/docs/api/java/util/TreeSet.html#TreeSet-java.util.Comparator-
If you don't want them actually sorted, but just remove dupes, the comparator just has to return 0 when they are equal.
TreeSet<Course> tree1 = new TreeSet<Course>((c1, c2) -> c1.number==c2.number && c1.Name.equals(c2.Name) ? 0 : 1);
and
TreeSet<Course> tree2 = new TreeSet<Course>((c1, c2) -> c1.Name.equals(c2.Name) ? 0 : 1);
You can wrap your class in a wrapper class that will implement the hashcode and equals functions the way you want:
public NameWrapper {
private Course c;
public NameWrapper(Course c) {
this.c = c;
}
public void equals(Object other) {
// ...
return this.name.equals(other.name);
}
// + hashCode
// + getter
}
// Similarly with number and name wrapper
And then you can wrap, distinct and unwrap your elements:
Collection<Course> courses = // ...
Collection<Course> distincts =
courses.stream()
.map(NameWrapper::new) // wrap
.distinct()
.map(NameWrapper::getCourse) // unwrap
.map(NumberNameWrapper::new) // wrap
.distinct()
.map(NumberNameWrapper::getCourse) // unwrap
.collect(Collectors.toList())
One easy, but probably not really great solution would be to use two specific wrapper classes that each have different equals methods.
And instead of directly using your own class, you put objects of those "wrapper" classes into those collections.
Like:
class Course { ... your class
class CourseWrapperForName {
Course wrappedCourse;
...
Course getWrappedCourse() { return wrappedCourse; }
#Override
public boolean equals(Object other) {
... compares names
class CourseWrapperForNumber {
Course wrappedCourse;
...
#Override
public boolean equals(Object other) {
... compares numbers
Now, eliminating duplicates can be done by putting your Course objects into the corresponding wrapper; adding wrappers to Sets; and then retrieving the course.
But obviously, that is a lot of boilerplate; and more reasonable solutions could be
A) using a TreeSet with a different
B) the later can be enhanced with a lot of black lambda magic; there is a nice presentation how to do that (it is in German, but mainly code; the interesting part starts at page 40).
I would take the Set<Course> with this equals method implemented (that will give me the course which are unique in name & number both).
Further, I would make a subclass of Course 'SubCourse' and override the equals method:
class SubCourse extends Course{
public boolean equals(Object o){
if(o instanceof SubCourse){
return (this.Name.equals(((SubCourse)o).Name));
}else{
return false;
}
}
}
And then make a Set<SubCourse> that will give you a unique courses in terms of numbers (not in name as we excluded that condition). You need to make the instance variables of Course as protected.

TreeSet storing duplicate custom objects

Hello I probably oversaw something, but here it goes.
I have a TreeSet<CustomObject> and I do not want to have duplicates in the Set. My CustomObject class looks like this.
class CustomObject implements Comparable<CustomObject> {
String product;
String ean;
public CustomObject(String ean){
this.ean = ean;
// product is getting set via setter and can be null
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CustomObject that = (CustomObject) o;
return ean.equals(that.ean);
}
#Override
public int hashCode() {
return ean.hashCode();
}
#Override
public int compareTo(CustomObject another) {
if(equals(another)) return 0;
if(product != null && another.product == null) return -1;
if(product == null) return 1;
return product.compareToIgnoreCase(another.product);
}
}
Now I have a add Function for new objects.
private final TreeSet<CustomObject> productCatalog;
public void addObject(SomeData tag) {
CustomObject p = new CustomObject(tag.getEan());
if (productCatalog.contains(p)) { // <-- This checks only one entry of the Set.
for (CustomObject temp : productCatalog) {
if (temp.equals(p)) {
p = temp; // I do stuff with that later which is irrelevent here
}
}
} else {
productCatalog.add(p);
}
}
The method productCatalog.contains(p) calls the compareTo method from the Comparable Interface and does the comparing. The issue here is that it literally only checks I think the last object? in the set. So what happens is that only one unique CustomObject entry is present.
This is the scenario when I follow it with the debugger:
productCatalog.contains(p)
calls compareTo
calls equals to check if ean.equals(that.ean)
returns once true, but every other time false. Since it only checks the last object
How can I have it to check not only one object in step 4, but all the present objects in the Set. What am I missing?
Thx!
EDIT: These are some sample data. For the simplicity SomeData tag is basically a String.
First run:
addObject("Ean1") // success added
addObject("Ean2") // success added
addObject("Ean3") // success added
addObject("Ean4") // success added
Everything gets added into the TreeSet.
Second run:
addObject("Ean1") // failed already in the map
addObject("Ean2") // failed already in the map
addObject("Ean3") // failed already in the map
addObject("Ean5") // success added
addObject("Ean4") // success added
addObject("Ean4") // success added
For testing purpose I manually set product names depending on the String ean.
public CustomObject(String ean){
this.ean = ean;
switch(ean){
case "Ean1": product = "TestProduct"; break;
case "Ean2": product = "ProductTest";break;
case "Ean3": product = "Product";break;
}
The TreeSet acts as a cache.
Edit2: This is how I solved it.
for (CustomObject temp : productCatalog) {
if (temp.equals(p)) {
p = temp; // I do stuff with that later which is irrelevent here
}
}
I removed the if statement with the contains method since that would always return ยด1or-1in my special case. Now I simply iterate over the Set to correctly use theequals` method since the TreeSet uses compareTo() for checking every element in the Set.
The Java Docs state the following
Note that the ordering maintained by a set (whether or not an explicit
comparator is provided) must be consistent with equals if it is to
correctly implement the Set interface. (See Comparable or Comparator
for a precise definition of consistent with equals.) This is so
because the Set interface is defined in terms of the equals operation,
but a TreeSet instance performs all element comparisons using its
compareTo (or compare) method, so two elements that are deemed equal
by this method are, from the standpoint of the set, equal. The
behavior of a set is well-defined even if its ordering is inconsistent
with equals; it just fails to obey the general contract of the Set
interface.
The main problem:
compareTo does return 1 if both product and other.product are null. This is wrong because they are actually equal. You probably forgot to set product names for the higher ean values, like "Ean4" and "Ean5".
Old answer:
Your implementations of equals and compareTo do not fit together.
equals works on the ean and compareTo on the product. This only works if you implicitly assume that equal ean imply equal product. If this is not true in your test cases, the result will be wrong.
In either case, it is no good implementation because this can lead to a < b, b < c but a "equals" c.

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