I have created an arraylist and I need to create a new object and compare the attributes of that object to the attributes of the other elements in the array. What would be an example code if my arraylist is array, the object is object1 and the attribute is item?
2 Answers
It's hard to answer this question with only the information you've provided, but you are probably looking for something like this:
for (MyClass o : array) {
if (o.item > object1.item) { // or any other such comparison
... // do something
}
}
We loop over each element of your ArrayList (named array) using a for-each loop and, in every iteration, we compare the element of array with object1.
Edit Based on the OP's comment, something like this could be tried:
for (int i = 0 ; i < array.size() ; i++) {
if (object1.attribute < array.get(i).attribute) {
array.add(object1);
}
}
Or, more concise:
for (MyClass o : array) {
if (object1.attribute < o.attribute) {
array.add(object1);
}
}
2 Comments
Alex Mendez
That is what I have: for(int i=0; i<array.size(); i++) { if (object1.attribute < array.attribute) { array.add(object); } } Would that work?
arshajii
You would want
object1.attribute < array.get(i).attribute. Also, I assume you mean array.add(object1)? See my edit above.What I would do would be to create a new object, and use that object to fill the Arraylist. Like this
public class MyElement {
int attr1;
String attr2;
public MyElement(int attr1, String attr2) {
// do stuff to store these attributes.
}
public boolean isEqual(MyElement comparisonElement) {
// compare attributes
if (this.attr1 == comparisonElement.attr1 && this.attr2 = comparisonElement.attr2) {
return true;
}
return false;
}
}
In your other class, the one containing the arraylist and wishing to do the comparisons
// create arraylist
ArrayList<MyElement> alme = new ArrayList<MyElement>()
// do loop and comparison(s)
1 Comment
arshajii
public class MyElement() --> public class MyElement.