Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if the elements in an Array List are same or different?

I'm trying to verify if all the elements in an array list are same or not. This is my code:

ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(2,2,4,2));
for (int z = 0; z < arr.size(); z++) {          
    if(!arr.get(z++).equals(arr.get(z--))) {
        System.out.println("same"); 
    }else {
        System.out.println("differnt");         
    }
}
like image 615
user10274438 Avatar asked Feb 16 '19 11:02

user10274438


1 Answers

Put the elements into a Set. If the resulting set has a size of 1, then all elements have been the same. One line of code, no loops, no indices, works with every collection:

boolean allTheSame = new HashSet<Integer>(list).size() == 1;
System.out.println(allTheSame ? "same" : "different");

(Edited:)

It might be worth noting that if the list is large, and likely contains many different elements, then constructing a Set will impose some memory overhead that can be avoided, if desired. In this case, you'd iterate over the list and compare all elements to the first one. But you should not check the elements for identity with ==. Instead, you should compare them using their equals method, or, if you graciously want to handle null entries, using Objects#equals.

An example of how to solve this efficiently and generically is given in the answer by Zabuza

like image 188
Marco13 Avatar answered Oct 07 '22 19:10

Marco13