I have an Arraylist
ArrayList<WorkPosition> info = new ArrayList<>();
where in some point, I add some objects. At the end this arrayList has the same object multiple times.. The object has some int values and 2 arraylists
97 [9, 10, 15] [1202, 1204, 2082]
97 [9, 10, 15] [1202, 1204, 2082]
97 [9, 10, 15] [1202, 1204, 2082]
42 [14, 16, 29] [404, 1081, 1201D]
42 [14, 16, 29] [404, 1081, 1201D]
42 [14, 16, 29] [404, 1081, 1201D]
57 [18, 30, 32] [2081, 435, 1032]
57 [18, 30, 32] [2081, 435, 1032]
57 [18, 30, 32] [2081, 435, 1032]
34 [19, 27, 28] [4501, 831, 201]
34 [19, 27, 28] [4501, 831, 201]
34 [19, 27, 28] [4501, 831, 201]
Is there any way to delete the extra appearances?
I read this How do I remove repeated elements from ArrayList? but in my case I don't have Strings but objects type of WorkPosition..
public class WorkPosition {
private int id;
ArrayList<Integer> machines = new ArrayList<>();
ArrayList<String> bottles= new ArrayList<>();
public WorkPosition(int id, ArrayList<Integer> machines, ArrayList<String> bottles) {
this.id = id;
this.machines = machines;
this.kaloupia = kaloupia;
}
//getters and setters...
}
I read this How do I remove repeated elements from
ArrayList? but in my case I don't haveStrings but objects type ofWorkPosition
Since the solution from the answer does not care if you use Strings or some other well-behaved objects, all you need to do is making your WorkPosition objects well-behaved from the point of view of the solution.
To that end, you have to override two specific methods - hashCode() and equals(Object), and make sure that they behave according to specification. Once this is done, the method of eliminating duplicates is going to work for your objects as well as it does for Strings.
class WorkPosition {
@Override
public boolean equals(Object obj) {
// The implementation has to check that obj is WorkPosition,
// and then compare the content of its attributes and arrays
// to the corresponding elements of this object
...
}
@Override
public int hashCode() {
// The implementation needs to produce an int based on
// the values set in object's fields and arrays.
// The actual number does not matter too much, as long as
// the same number is produced for objects that are equal.
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With