Question

I want to compare elements in two list using < > ==

Is it the right way to use intValue()?

List<Integer> a = new ArrayList<Integer>();
a.add(129);

List<Integer> b = new ArrayList<Integer>();
b.add(128);

if(a.get(0).intValue() > b.get(o).intValue()) {
   // something
}
Was it helpful?

Solution

You're making it the right way.

As stated in the comments, you could also you compareTo(). An alternative to compareTo() is equals() which won't throw a NullPointerException in the case where the object is null.

OTHER TIPS

Your way is correct. But with a small correction.

1)

a.get(0).intValue() == b.get(0).intValue()

2)

a.get(0).equals(b.get(0))

This is the problem in your code, you have to get(0), instead of get(1). Remember, in java it always start with 0.

Values can be compared using equals() or CompareTo method as well.

import java.util.ArrayList;
import java.util.List;

public class TestClass {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        List<Integer> a= new ArrayList<Integer>();
        a.add(128);

        List<Integer> b = new ArrayList<Integer>();
        b.add(128);

        if(a.get(0).intValue() == b.get(0).intValue()){
            System.out.println("success");
        }else{
            System.out.println("failure");
        }
        if(a.get(0).equals(b.get(0))){
            System.out.println("success");
        }else{
            System.out.println("failure");
        }

    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top