Example of ArrayList

Let's say we have an array with duplicate numbers, such as {4, 5, 5, 5, 4, 6, 6, 9, 4}, and we want to print out the unique number from this, and how many times this number is repeated in this array. Our output should be "four is repeated three times, five is repeated three times, six twice, nine once."

Let's bring in the ArrayList concept here to solve this puzzle:

package demopack;
import java.util.ArrayList;
public class collectiondemo {
public static void main(String[] args) {
int a[] ={ 4,5,5,5,4,6,6,9,4};
ArrayList<Integer>ab =new ArrayList<Integer>();
for(int i=0;i<a.length;i++)
{
int k=0;
if(!ab.contains(a[i]))
{
ab.add(a[i]);
k++;
for(int j=i+1;j<a.length;j++)
{
if(a[i]==a[j])
{
k++;
}
}
System.out.println(a[i]);
System.out.println(k);
if(k==1)
System.out.println(a[i]+"is unique number");
}
}
}
}

The preceding snippet is the entire code required to solve this puzzle. Let's try to understand the key logical concepts within the code. We start by defining the array and then create an empty ArrayList with the ab object type. Then we create a for loop, and within it we use an if loop with !ab.contains to check whether the element is present within the loop. We need another for loop within this if loop to iterate through the remaining part of the array. The if loop within this for loop will work as a counter for us to increment the number of times a number is repeated in the array.

We're done with the for and if loops. We print out each element from the array and the number of instances each element is present in the array. To print the unique number, that is, the number that is not repeated in the array, we use an if loop and print it. 

That's it for this example; you can try coding this example with your own logic.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.83.150