I have a class that implements a 2Dtable. The elements in the table is generic. And the table is stored like this:
public Object[][] list;
The problem is that calling clone on this apparently doesn't work. Note that my testcase initializes the table to store normal Integers.
Tabell2D<Integer> en = new Tabell2D<Integer>(5,5);
en.sett(0, 0, 55);
Tabell2D<Integer> to = en.clone();
to.sett(0, 0, 11);
assertTrue(en.equals(to));
Here I make a table. Change it, clone it. Change the clone, and compare them.
Obviously the clone is changed. Even so, this assertTrue is well true.
The equal method is generated by eclipse:
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Tabell2D other = (Tabell2D) obj;
if (bredde == null) {
if (other.bredde != null)
return false;
} else if (!bredde.equals(other.bredde))
return false;
if (høyde == null) {
if (other.høyde != null)
return false;
} else if (!høyde.equals(other.høyde))
return false;
if (!Arrays.equals(liste, other.liste))
return false;
return true;
}
I assume that the problem is either in the compare of the list variable in equal, or the problem is in the clone method.
Clone method:
public Tabell2D<E> clone(){
Tabell2D<E> nyTab = new Tabell2D<E>(this.bredde,this.bredde);
nyTab.liste = liste.clone();
return nyTab;
}
I think that the root of the problem is that cloning a 2d array doesn't go deep. If you want a deep copy of 'liste' you need to write your own code to copy each row (or column depending on how you look at it).
Clone is supposed to return Object. Your "clone" isn't overriding the normal one.
Also, I don't know that cloning an array does a deep copy. You'd probably be better off to create a new array and assign the elements.
Related
So I overwrote an equals function that works with Nodes that contain objects. and it looks like this.
#Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
// Checks if obj is from the same class as this Deque.
if (obj.getClass() != this.getClass()) return false;
#SuppressWarnings("unchecked")
// If obj is from the same class, casts object to DoublyLinkedDeque.
DoublyLinkedDeque<T> object = (DoublyLinkedDeque<T>) obj;
Node other = object.front;
Node self = this.front;
// Checks the info of every Node in this Deque with the other.
while (self != null && other != null) { // Checks
if (!(self.info.equals(other.info))) return false;
self = self.next;
other = other.next;
}
// Otherwise, checks if the front of both Deques is null.
return (self == null && other == null);
}
And it works but I'm not sure how the second invocation of equals work. Specifically how does my code check if the info field (that contains objects) of two nodes are equal without calling super.equals? Nothing in my function has the capability to check if two objects are equal as far as I know, can someone explain this?
I want to find a LegalEntity object in an ArrayList. The object can possibly be a different instance. I'm only interested in whether they represent the same value, i.e. they have the same primary key. All LegalEntity instances are created from database values by EJB:
List<LegalEntity> allLegalEntities = myEJB.getLegalEntityfindAll());
LegalEntity currentLegalEntity = myEJB.getLegalEntityfindById(123L);
My first naive idea never finds matches:
if (allLegalEntities.contains(currentLegalEntity)) {
}
I then thought that perhaps I need to create my own equals() method:
public boolean equals(LegalEntity other) {
return legalEntityId.equals(other.legalEntityId);
}
But this method is not even being invoked. Is there a way to find an object in a list that doesn't involve looping?
I'm learning Java so it might easily be some foolish misunderstanding on my side.
Your approach is correct, but you need to override the method equals that accepts an Object:
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
LegalEntity other = (LegalEntity) obj;
// check if equals based one some properties
}
However you also need to override hashCode:
#Override
public int hashCode() {
// return a unique int
}
So this might not be the easiest solution.
Another approach is to use filter:
LegalEntity myLegalEntity = myEJB.getLegalEntityfindAll().stream()
.filter(legalEntity -> legalEntity.getProperty().equals("someting"))
.findAny()
.orElse(null);
More info here
If you're using Java 8 you can use streams:
List<LegalEntity> allLegalEntities = myEJB.getLegalEntityfindAll());
LegalEntity currentLegalEntity = allLegalEntities.stream().filter(entity -> entity.getId() == 123L).findFirst();
This question ask many times in stackoverflow and i tried all masters answers.
But list.contain() return always false.
and also overide equal() method.
Here is my pojo class
public class RecentStickerPojo
{
File stickerName;
File folderName;
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RecentStickerPojo other = (RecentStickerPojo) obj;
if (folderName != other.folderName&&stickerName!=other.stickerName)
return false;
return true;
}
}
in activity class
RecentStickerPojo recentStickerPojo=new RecentStickerPojo();
recentStickerPojo.setStickerName(s1);
recentStickerPojo.setFolderName(f1);
list.contains(recentStickerPojo) // return false
Don't forget to implement hashcode.
For strings, use equals (or !equals) and not == (or !=)
Also the equals' last 3 lines can be changed to:
return (folderName.equals(other.folderName) && stickerName.equals( other.stickerName);
No need to override hashcode, as List contains method will use equals method for comparing object. It seems you are comparing File objects directly which can be different. Yes, try by changing last comparison,
if (folderName.equals(other.folderName) && stickerName.equals(other.stickerName))
i am trying to test singly linked list using Assert.assertEqual(expected, actual) the linked list has a node index and a value. how can i use Assert.assertEquals() to test it.
This is my code
#Test
void nonEmptyTest() throws ListAccessError {
SingleLinkedList<Integer> list = new SingleLinkedList<Integer>();
SingleLinkedList<Integer> expList = new SingleLinkedList<Integer>();
list.add(0,10);
list.add(1,20);
list.add(2,30);
expList.add(0,10);
expList.add(1,20);
expList.add(2,30);
Assert.assertEquals(expList, list);
}
You need to override boolean equals(Object obj) method for you to expect the assert on the actual values of the list.
Here's a sample on how to override
(Note: I don't know your implementation of SingleLinkedList, you can get an idea from the following code and implement accordingly)
#Override
public boolean equals(Object obj) {
if (obj == null)
return false;
SingleLinkedList<Integer> listToCompare = (SingleLinkedList<Integer>) obj;
SingleLinkedList<Integer> thisList = this;
while (listToCompare != null && thisList != null) {
if (!listToCompare.getData().equals(thisList.getData()))
return false;
listToCompare = listToCompare.getNext();
thisList = thisList.getNext();
}
if (listToCompare == null && thisList == null)
return true;
return false;
}
If you want to compare two different objects to find out whether they're equal, your class that defines those objects generally needs to implement the equals() method. Otherwise Java has no way to know what 'equality' is supposed to mean.
That is, your problem is not in the unit test, it's in the class being tested. The
unit test did its job :-)
I have 2 classes.
public class klass1 {
String bir;
String myID;
klass1(String bir, String myID)
{
this.bir=bir;
this.myID=myID;
}
}
.
import java.util.*;
public class dd {
public static void main(String[] args) {
ArrayList<Object> ar=new ArrayList();
ar.add(new klass1("wer","32"));
ar.add(new klass1("das","23"));
ar.add(new klass1("vz","45"));
ar.add(new klass1("yte","12"));
ar.add(new klass1("rwwer","43"));
ar.remove(new klass1("vz","45"));//it's not worked!!!
System.out.println(ar.size());
}
}
What I want is removing or getting an object from array list with object's second attribute. How can I do that? Is there an easy way for it?
Just implement the equals method in the class Klass1.
public class Klass1 {
String bir;
String myID;
Klass1(String bir, String myID)
{
this.bir=bir;
this.myID=myID;
}
public boolean equals(Object o){
if(o instanceof Klass1)
return ((Klass1)o).myID.equals(myID);
else
return false;
}
}
Its because you are trying to delete a new object which isnt in the arraylist. When you use new klass1("vz","45") you are creating a new instance of this class which isnt in the arraylist.
What the system does internally is to compare those classes using equals. Why this doesn't work is explained in the following code:
Object o1 = new Object();
Object o2 = new Object();
System.out.println(o1 == o2); // false, obviously
System.out.println(o1.equals(o2)); // false
System.out.println(o1); // java.lang.Object#17046822
System.out.println(o2); // java.lang.Object#22509bfc
You can tell by the number following the # that these objects have a different hash values, and this is what the equals function of Object does check.
This is relevant for your klass, because unless you overwrite equals, you will use the equals of Object. And if you implement equals you should always implement hashcode as well. Because both tell you something about whether or not two objects are the "same", and if the one says something else than the other, some part of your code might get confused.
How to properly implement equals for your class:
#Override
public int hashCode() {
int hash = 7;
hash = 17 * hash + Objects.hashCode(this.bir);
hash = 17 * hash + Objects.hashCode(this.myID);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final klass1 other = (klass1) obj;
if (!Objects.equals(this.bir, other.bir)) {
return false;
}
if (!Objects.equals(this.myID, other.myID)) {
return false;
}
return true;
}
This can be done in most IDEs btw with a shortcut (i.E. alt-insert in Netbeans). Note that I did this in Java 7 using Objects. If you are in Java 6, you need to manually type(a == b) || (a != null && a.equals(b)); with the appropriate objects to compare.
Creating a proper hashcode is not always trivial, for more complex objects you might want to read a bit about hashcodes first. For simple objects: multiply primes with something.
The equals method is usually trivial, it is just important to first check for null and for class equality. This is often forgotten by programmers and a common source for NullPointerExceptions and ClassCastExceptions.