EDITED/SOLVED still looking for better answer
I do have a answer here How do I remove repeated elements from ArrayList? and it is working my question is relation to ONLY list and not Set. Since through out application flow list has been implemented and it is difficult for me to change all List references to Set reference as https://docs.oracle.com/javase/7/docs/api/java/util/List.html has get(..) Set doesn't have get(..).
Each object getting added is a new Instance.
hi i Have a model class
public final class MyClass implements Comparable<MyClass> {
public static final int APP = 0;
public static final int FILE = 1;
public static final int FOLDER = 2;
private String name;
private String path;
private String pkg;
private Long size;
private boolean selected;
private Integer type;
public MyClass(String name, String path, String pkg, Long size, boolean selected, int type) {
this.name = name;
this.path = path;
this.pkg = pkg;
this.size = size;
this.selected = selected;
this.type = type;
if (!TextUtils.isEmpty(path)) {
File file = new File(path);
if (file.exists()) {
this.size = file.length();
}
}
}
public String getName() {
return name;
}
public String getPath() {
return path;
}
public String getSize() {
return FileUtils.getReadableFileSize(size);
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public Integer getType() {
return type;
}
public String getPkg() {
return pkg;
}
#Override
public String toString() {
return "{Pkg=" + pkg + ", Path=" + path + ", size=" + size + ", hashcode: " + hashCode() +"}";
}
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
MyClass myclass = (MyClass) o;
if (path != null ? !path.equals(myclass.path) : myclass.path != null)
return false;
if (pkg != null ? !pkg.equals(myclass.pkg) : myclass.pkg != null)
return false;
return size != null ? size.equals(myclass.size) : myclass.size == null;
}
#Override
public int hashCode() {
int result = path != null ? path.hashCode() : 0;
result = 31 * result + (pkg != null ? pkg.hashCode() : 0);
result = 31 * result + (size != null ? size.hashCode() : 0);
return result;
}
#Override
public int compareTo(MyClass myclass) {
return myclass.getType().compareTo(this.type);
}
}
But when i create common object, these object are getting added to list, even though their hashcode is same it is duplicate in list. Anything i may be doing wrong here.
Output of toString of List is as follows:
[{
Pkg = com.a.bc,
Path = /data/app / com.a.bc - 1 / base.apk,
size = 1800820,
hashcode: -908060882
}, {
Pkg = com.a.b.c,
Path = /data/app / com.a.b.c - 1 / base.apk,
size = 21279534,
hashcode: 1116685502
}, {
Pkg = com.a.b.c,
Path = /data/app / com.a.b.c - 1 / base.apk,
size = 21279534,
hashcode: 1116685502
}]
Here is some dirty implementation but this is not what i was looking for...
private final class DuplicateFilterArrayList<E> extends ArrayList<E> {
private DuplicateFilterArrayList() {
}
#Override
public boolean add(E object) {
if (object instanceof MyClass) {
if (!contains(object)) {
return super.add(object);
} else {
Logger.error(TAG, "Object already exists go home");
return false;
}
} else {
throw new IllegalArgumentException("Unsupported Object type " + object.getClass().getSimpleName());
}
}
#Override
public boolean contains(Object object) {
if (object instanceof MyClass) {
MyClass otherMyClassObjec = (MyClass) object;
for (E myClassItem : this) {
MyClass newMyClass = (MyClass) myClassItem;
if (newMyClass.equals(otherMyClassObjec) && newMyClass.hashCode() == otherMyClassObjec.hashCode()) {
return true;
}
}
}
return false;
}
}
Before adding to the list, check if the instance is already in the Collection by using the contains method on the Collection (List in this case). Then you can choose to not add again if it's already contained. It should work if you've correctly implemented the equals and hashCode methods.
Create your own class(MYArrayList) which extend ArrayList. Make return type as list itself. Rest all will be same.
List list = new MyArrayList
MyArrayList extends ArrayList<>
override add method of MyArrayList such that before adding MYClass in List its Check if this List contains it already or not.
But remember this will degrade the performance since it will iterate over all elements in list just to check duplicacy in insertion.
Related
This question already has answers here:
Implementing equals and hashCode for objects with circular references in Java
(4 answers)
Closed 3 years ago.
I'm trying to calculate hashcode of one class, but I got stackoverflow. How can I do this correctly? I genered it by IntelliJ idea, but still. Got stackoverflow, I know the reason (probably) but I really want to calculate proper hashcode..
public class Main {
public static void main(String[] args) {
TestA testA = new TestA();
TestB testB = new TestB();
testA.id = 1;
testA.name = "test";
testA.testB = testB;
testB.testA = testA;
testB.id = 1;
testB.name = "test";
System.out.println(testA.hashCode());
}
}
class TestB {
int id;
String name;
TestA testA;
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof TestB)) return false;
TestB testB = (TestB) o;
if (id != testB.id) return false;
if (name != null ? !name.equals(testB.name) : testB.name != null) return false;
return testA != null ? testA.equals(testB.testA) : testB.testA == null;
}
#Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (testA != null ? testA.hashCode() : 0);
return result;
}
}
class TestA {
int id;
String name;
TestB testB;
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof TestA)) return false;
TestA testA = (TestA) o;
if (id != testA.id) return false;
if (name != null ? !name.equals(testA.name) : testA.name != null) return false;
return testB != null ? testB.equals(testA.testB) : testA.testB == null;
}
#Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (testB != null ? testB.hashCode() : 0);
return result;
}
}
I included main function too. You can easily open this..
What you are looking for is a way to walk the object tree without entering into an infinite loop. This can be achieved by storing the visited objects in a thread-local Set and stopping when entering a hashcode while this is in that set.
And you can't just willy-nilly use a HashSet to store the 'visited' objects, because it internally calls your hashcode so the problem is just shifted elsewhere and you still get a stack overflow. Luckily there's a container that uses identity instead of equality, however it's the Map variant, not the Set. Ideally you want IdentityHashSet, but it doesn't exist, however the still useful IdentityHashMap exists. Just use the keys as the actual contents and use dummy values.
public class Main {
public static void main(String[] args) {
TestA testA = new TestA();
TestB testB = new TestB();
testA.id = 1;
testA.name = "test";
testA.testB = testB;
testB.testA = testA;
testB.id = 1;
testB.name = "test";
System.out.println(testA.hashCode());
}
}
class TestB {
int id;
String name;
TestA testA;
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TestB))
return false;
TestB testB = (TestB)o;
if (id != testB.id)
return false;
if (name != null ? !name.equals(testB.name) : testB.name != null)
return false;
return testA != null ? testA.equals(testB.testA) : testB.testA == null;
}
private static final ThreadLocal<Set<Object>> VISITED = ThreadLocal.withInitial(() -> new HashSet(10));
#Override
public int hashCode() {
Set<Object> visited = VISITED.get();
if (visited.contains(this))
return 0;
visited.add(this);
try {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (testA != null ? testA.hashCode() : 0);
return result;
} finally {
visited.remove(this);
}
}
}
class TestA {
int id;
String name;
TestB testB;
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TestA))
return false;
TestA testA = (TestA)o;
if (id != testA.id)
return false;
if (name != null ? !name.equals(testA.name) : testA.name != null)
return false;
return testB != null ? testB.equals(testA.testB) : testA.testB == null;
}
private static final ThreadLocal<Map<Object, Object>> VISITED =
ThreadLocal.withInitial(() -> new IdentityHashMap<>(10));
#Override
public int hashCode() {
Map<Object, Object> visited = VISITED.get();
if (visited.containsKey(this))
return 0;
visited.put(this, this);
try {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (testB != null ? testB.hashCode() : 0);
return result;
} finally {
visited.remove(this);
}
}
}
Note: The two VISITED variables can be a single variable, but since your classes don't have a common superclass (other than Object) I had to make two of them.
Caveat: When the tree contains multiple times the same instance of a class, the hashcode of that instance will be calculated multiple times. This is because everytime that instance is done visiting, it's removed from the list. This is because you don't want hard references to these instances to remain in the thread-local Map, preventing garbage collection.
I have the problem, that my equals method doesnt work as i want it to. I want to implement a deterministic turing machine, so I want to add the method findCommand(), which searchs through a arraylist of commands. So I decided to create a searchDummy to find all Transitions that are available for the Configuration I have.
Class States:
public class States {
private int stateId;
private boolean rejState;
private boolean accState;
private boolean stopState;
private List<Commands> commands = new ArrayList<Commands>();
equals in class States:
#Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof States) {
States otherState = (States) other;
return (stateId == otherState.stateId);
} else {
return false;
}
}
hashCode:
#Override public int hashCode() {
StringBuilder b = new StringBuilder(stateId);
return b.toString().hashCode();
}
this is the findCommand method in States:
public Commands findCommand(States state, char inputTapeChar,
char[] tapeChars) {
Commands searchDummy = new Commands(state, inputTapeChar, tapeChars,
null, null, null, null);
int pos = commands.indexOf(searchDummy);
return pos >= 0 ? commands.get(pos) : null;
}
commands is my arraylist, so I want to find the searchDummy with indexOf().
I have the class Commands, which holds the attribute Configuration configuration, the class Configuration, which holds the attributes of a Configuration and the attribute Transition transition and the class transition that holds the attributes for itself.
Class Commands:
public class Commands implements Comparable<Commands> {
private Configuration configuration;
Class Configuration:
public class Configuration {
private Transition transition;
private States state;
private char inputTapeChar;
private char[] tapeChars;
Class Transition:
public class Transition {
private States targetState;
private Direction inputTapeHeadMove;
private char[] newTapeChars;
private Direction[] tapeHeadMoves;
i have this equals method in Commands:
#Override public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof Commands) {
Commands otherCmd = (Commands) other;
return (configuration.equals(otherCmd.configuration));
} else {
return false;
}
}
and this hashcode
#Override
public int hashCode() {
StringBuilder b = new StringBuilder(configuration.getState() + ","
+ configuration.getInputTapeChar());
for (char c : configuration.getTapeChars()) {
b.append("," + c);
}
return b.toString().hashCode();
}
then almost the same in Configuration:
#Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof Configuration) {
Configuration otherConfi = (Configuration) other;
return (state.equals(otherConfi.state))
&& (inputTapeChar == otherConfi.inputTapeChar)
&& (Arrays.equals(tapeChars, otherConfi.tapeChars));
} else {
return false;
}
}
hashcode:
#Override
public int hashCode() {
StringBuilder b = new StringBuilder(state + "," + inputTapeChar);
for (char c : tapeChars) {
b.append("," + c);
}
return b.toString().hashCode();
}
equales in class State:
#Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof States) {
States otherState = (States) other;
return (stateId == otherState.stateId);
} else {
return false;
}
}
so my question:
when I debug this it goes through until it's finished with the checks but when it should return the value it stucks at Configuration.equals(...) and shows the error no source found!
what is the problem? Are the hashcodes wrong? Or are the equals wrong?
I never used equals before so I dont know when i need to use it or how i need to fix this. thanks for your help.
Your hashCode implementation looks suspect - all that String stuff is not standard.
For example for your Transition class should be something like this:
#Override
public int hashCode() {
int result = 17;
result = 31 * result + targetState.hashCode();
result = 31 * result + inputTapeHeadMove.hashCode();
result = 31 * result + newTapeChars.hashCode();
result = 31 * tapeHeadMoves.hashCode();
return result;
}
Most IDEs will offer autogen of hashCode and equals methods.
I have 2 custom Java classes;
private MyCustomClass1 obj1;
private MyCustomClass2 obj2;
Each of them has multiple attributes as below;
MyCustomClass1 {
attr1,
attr2,
commonattrId,
attr3
}
MyCustomClass2 {
attr4,
attr5,
commonattrId,
attr6
}
So as you can see, there is a common attribute in each of them (commonattrId) which just to add is a Long
There is also a composite class defined as below;
MyCompositeClass {
MyCustomClass1 obj1;
MyCustomClass2 obj2;
}
Now one of my query execution returns below list;
List myList1
and there is another query execution which returns me below list;
List myList2
My question is can I combine the above 2 lists given I have a commonattrId ?
slightly long but the idea is to override equals in MyClass1 and MyClass2:
public static void main(String[] args) throws IOException {
List<MyClass1> myClass1s = new ArrayList<MyClass1>();
myClass1s.add(new MyClass1(1, 1));
myClass1s.add(new MyClass1(2, 2));
List<MyClass2> myClass2s = new ArrayList<MyClass2>();
myClass2s.add(new MyClass2(3, 1));
myClass2s.add(new MyClass2(4, 2));
List<MyComposite> allMyClasses = new ArrayList<MyComposite>();
for(MyClass1 m : myClass1s) { // note: you should take the shorte of the two lists
int index = myClass2s.indexOf(m);
if(index != -1) {
allMyClasses.add(new MyComposite(m, myClass2s.get(index)));
}
}
System.out.println(allMyClasses);
}
static class MyClass1 {
int attr1;
long commonAttrId;
public MyClass1(int attr, long commonAttr) {
this.attr1 = attr;
this.commonAttrId = commonAttr;
}
#Override
public int hashCode() {
int hash = 5;
hash = 83 * hash + (int) (this.commonAttrId ^ (this.commonAttrId >>> 32));
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if(obj instanceof MyClass2) {
return this.commonAttrId == ((MyClass2)obj).commonAttrId;
}
if(obj instanceof MyClass1) {
return this.commonAttrId == ((MyClass1)obj).commonAttrId;
}
return false;
}
#Override
public String toString() {
return "attr1=" + attr1 + ", commonAttrId=" + commonAttrId;
}
}
static class MyClass2 {
int attr2;
long commonAttrId;
public MyClass2(int attr, long commonAttr) {
this.attr2 = attr;
this.commonAttrId = commonAttr;
}
#Override
public int hashCode() {
int hash = 5;
hash = 83 * hash + (int) (this.commonAttrId ^ (this.commonAttrId >>> 32));
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if(obj instanceof MyClass1) {
return this.commonAttrId == ((MyClass1)obj).commonAttrId;
}
if(obj instanceof MyClass2) {
return this.commonAttrId == ((MyClass2)obj).commonAttrId;
}
return false;
}
#Override
public String toString() {
return "attr2=" + attr2 + ", commonAttrId=" + commonAttrId;
}
}
static class MyComposite {
MyClass1 myClass1;
MyClass2 myClass2;
public MyComposite(MyClass1 a, MyClass2 b) {
myClass1 = a;
myClass2 = b;
}
#Override
public String toString() {
return "myClass1=" + myClass1 + ", myClass2=" + myClass2;
}
}
I don't know all the parameters of your problem but there are probably better ways to do this. For example: have both MyClass1 and MyClass2 inherit from a common class (i.e. MyBaseClass) and create a collection of that instead of the composite class MyCompositeClass.
Or instead of Lists you could have sets and create a set intersection.
You could create a map from id to the object for one of the lists and then iterate through the other to create the new List using the data from the map.
List<MyCompositeClass> combine(List<MyCustomClass1> myList1, List<MyCustomClass2> myList2) {
// create map
Map<Long, MyCustomClass1> idToObj = new HashMap<>();
for (MyCustomClass1 o : myList1) {
idToObj.put(o.commonattrId, o);
}
// construct result list
List<MyCompositeClass> result = new ArrayList<>();
for (MyCustomClass2 o : myList2) {
MyCustomClass1 o1 = map.get(o.commonattrId);
if (o1 != null) {
MyCompositeClass combined = new MyCompositeClass();
combined.obj1 = o1;
combined.obj2 = o;
result.add(combined);
}
}
return result;
}
This will only add all possible combinations of objects from both lists, if commonattrId values are pairwise distinct in each list, but since the field name has "Id" as suffix, I made an educated guess...
I have a HashMap that stores an object I created as a key and maps to an ArrayList of similar objects.
However, I am calling the get method, and using jGrasp's debugger I can clearly see that the key I am using in get() exists and indeed maps to an array but the only value I can get is a null value.
Here is where I am getting the null value.
public List<Entry> query(Record query) {
List<Entry> candList;
Entry key = new Entry(makeKey(query));
candList = map.get(key);
return candList;
}
Here is where I am populating the HashMap from a main store.
for(int i = 0; i < main.size(); i++) {
if(main.get(i).isActive()) {
values.clear();
tmp = new Entry(main.get(i).record());
key = new Entry(Record.make(tmp.entity(),tmp.relation(),wild));
if(!map.containsKey(key)) {
for(int v = 0; v < main.size(); v++) {
value = main.get(v);
if(key.entity().equals(value.entity()) && key.relation().equals(value.relation())) {
values.add(value);
}
}
map.put(key,new ArrayList(values));
}
}
}
Entry is a wrapper class that defaults to the equals() method of its inner object, here.
public boolean equals(Object o){
if(o == null){
return false;
}
else if(o instanceof Record){
Record r = (Record) o;
return this.entity.equals(r.entity) && this.relation.equals(r.relation) && this.property.equals(r.property);
}
else return false;
}
I also have a hashcode written for the object here.
int h = 0;
public int hashCode() {
int hash = h;
if(h != 0)
return hash;
String len = entity.concat(relation.concat(property));
for(int i = 0; i < len.length(); i++)
hash = hash * 31 +(int)len.charAt(i);
return hash;
}
For a little clarification, the Entry object holds an object of type Record that contains three immutable Strings, hence where the hashCode equation comes from.
For further clarification someone asked to see the entire Entry class.
private static class Entry {
private static boolean active;
private Record rec;
public Entry(Record r){
this.rec = r;
this.active = true;
}
public String entity() {
return rec.entity;
}
public String relation() {
return rec.relation;
}
public String property() {
return rec.property;
}
public Record record(){
return this.rec;
}
public boolean isActive(){
return this.active;
}
public void deactivate(){
this.active = false;
}
public void activate(){
this.active = true;
}
public boolean equals(Entry e) {
return this.rec.equals(e.record());
}
public int hashCode() {
return this.rec.hashCode();
}
public String toString() {
return rec.toString();
}
}
There are some collisions occurring in my HashMap but I know that's not supposed to be too much of an issue. Any ideas?
public boolean equals(Object o){
if(o == null){
return false;
}
else if(o instanceof Record){
Record r = (Record) o;
return this.entity.equals(r.entity) && this.relation.equals(r.relation) && this.property.equals(r.property);
}
else return false;
}
your Entry equals method may have some problem,what's the definition of relation?
the relation must be overwrite equals() and hashCode()
It's great to put all your code here,what's your main's definition?
and In your code there are many places contains maybe null pointer bug
your hashcode function might have a problem when setting the int to 0 (int h = 0) ... a good explanation can be found in Josh Bloch's Effectiv Java book (item 8).
Here is an example:
#Override
public int hashCode() {
int result = 17;
// this line should change depending on your fields
// let say you have a string property that is not null
result = 31 * result + property.hashCode();
return result;
}
... you can also use a library like Guava
#Override
public int hashCode() {
return Objects.hashCode(this.property1, this.property2);
}
This is my class:
public class MultiSet<E> extends AbstractCollection<E>
{
private int size = 0;
private Map<E, Integer> values = new HashMap<E, Integer>();
public MultiSet()
{
}
public MultiSet(Collection<E> c)
{
addAll(c);
}
#Override
public boolean add(E o)
{
throw new UnsupportedOperationException();
}
#Override
public boolean remove(Object o)
{
throw new UnsupportedOperationException();
}
public Iterator<E> iterator()
{
return new Iterator<E>()
{
private Iterator<E> iterator = values.keySet().iterator();
private int remaining = 0;
private E current = null;
public boolean hasNext()
{
return remaining > 0 || iterator.hasNext();
}
public E next()
{
if (remaining == 0)
{
remaining = values.get(current);
}
remaining--;
return current;
}
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
public boolean equals(Object object)
{
if (this == object) return true;
if (this == null) return false;
if (this.getClass() != object.getClass()) return false;
MultiSet<E> o = (MultiSet<E>) object;
return o.values.equals(values);
}
public int hashCode()
{
return values.hashCode()*163 + new Integer(size).hashCode()*389;
}
public String toString()
{
String res = "";
for (E e : values.keySet());
//res = ???;
return getClass().getName() + res;
}
public int size()
{
return size;
}
}
So basically, i need to implement my add/remove-methods correctly, to add or remove elements to/from the Set.
To me, it seems like my equals is correct, but Eclipse says that in the line:
MultiSet<E> o = (MultiSet<E>) object;
there is an unchecked cast from object to Multiset<E>
Any thoughts?
Also, in my toString method, i'm not 100% sure how to define "res"?
Thanks,
// Chris
use this instead:
MultiSet<?> o = (MultiSet<?>) object;
this is necessary due to how generics are implemented in java.