0

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?

0

2 Answers 2

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

That is what I have: for(int i=0; i<array.size(); i++) { if (object1.attribute < array.attribute) { array.add(object); } } Would that work?
You would want object1.attribute < array.get(i).attribute. Also, I assume you mean array.add(object1)? See my edit above.
0

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

public class MyElement() --> public class MyElement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.