Say I have an ArrayList containing the elements {1,2,3,4}, and I want to enumerate all possible combinations of two elements in the ArrayList. i.e. (1,2), (1,3), (1,4), (2,3), (2,4), (3,4). What is the most elegant way of going about doing this?
if i have 10 elements in a Arraylist how can i get 5th element? You can use get(index) method to access any element in arraylist. simply use get method.
nextInt() method of Random class can be used to generate a random value between 0 and the size of ArrayList. Now use this number as an index of the ArrayList. Use get () method to return a random element from the ArrayList using number generated from nextInt() method.
To get an element from ArrayList in Java, call get() method on this ArrayList. get() method takes index as an argument and returns the element present in the ArrayList at the index. E element = arraylist_1. get(index);
Nested for loops would work:
for (int i = 0; i < arrayList.size(); ++i) {
for (int j = i + 1; j < arrayList.size(); ++j) {
// Use arrayList.get(i) and arrayList.get(j).
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With