开发者

Comparing variables of objects in an array?

I've an array of objects in Java. Say these objects Obj contain a variable var, and I have several Obj stored in an array Array[].

I'd like to compare the var between two adjacent Obj but I don't know how, nor can I find any info online (which makes me think i'm working my question wrong or it's not doable or something)

Edit:

I'm currently attempting the rather roundabout method of assigning the array objects in question to new temporary objects and just doing the com开发者_运维知识库parison with those:

Obj o1 = o[i];
Obj o2 = o[i+1];

if (o1.var > o2.var)
//etc

But surely there is something better.


If you have an array of objects, you can do your comparison without creating the temporary references:

MyObject[] arr = //populated somehow
for (int index = 0; index < arr.length - 1; index++) {
  if (arr[index].var > arr[index + 1].var) {
    //your logic
  }
}

You might also want to take a look at the Comparable interface as a means of encapsulating the comparison of the objects based on a particular field. Using this interface would allow you to take advantage of its support in the Collections API.


Based on your edit, it would be fine to say

if (o[i].var > o[i+1].var) { ... }

assuming that o was of type Obj[].

I'm curious, though: are you trying to sort the array? If so, you can use Arrays.sort() (If not, it's a good method to know about anyway.)


I may not be understanding your question correctly, but the following is perfectly valid:

if (o[i].var > o[i+1].var )  { // ...etc... }

Beware of when you hit the end of the array! That is, if you are looping through all of the elements and i is the last one, then o[i+1] will give you an Array Index Out of Bounds error!


Just use them directly without the reference i.e. substitute the array lookup into where you are doing the comparison.

if (o[i].var > o[i+1].var) {
    // etc
}

Or in a loop, doing every one programmatically:

for (int i=0; i<o.length-1; i++) {
    if (o[i].var > o[i + 1].var) {
        // etc
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜