0

我创建了一个数组列表,我需要创建一个新对象并将该对象的属性与数组中其他元素的属性进行比较。如果我的arraylist 是array,对象是object1,属性是item,那么示例代码是什么?

4

2 回答 2

1

仅凭您提供的信息很难回答这个问题,但您可能正在寻找这样的东西:

for (MyClass o : array) {
    if (o.item > object1.item) {  // or any other such comparison 
        ...  // do something
    }
}

我们使用for-eachArrayList循环遍历您(named ) 的每个元素,并且在每次迭代中,我们比较with的元素。arrayarrayobject1

编辑根据 OP 的评论,可以尝试这样的事情:

for (int i = 0 ; i < array.size() ; i++) {
    if (object1.attribute < array.get(i).attribute) {
        array.add(object1); 
    } 
}

或者,更简洁:

for (MyClass o : array) {
    if (object1.attribute < o.attribute) {
        array.add(object1);
    }
}
于 2012-10-01T01:33:36.540 回答
0

我要做的是创建一个新对象,并使用该对象来填充 Arraylist。像这样

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;
    }
}

在您的另一类中,包含数组列表并希望进行比较的类

// create arraylist
ArrayList<MyElement> alme = new ArrayList<MyElement>()
// do loop and comparison(s)
于 2012-10-01T01:50:23.393 回答