In: Computer Science
Write a Console Java program that inserts 25 random integers in the range of 0 to 100 into a Linked List.
(Use SecureRandom class from java.security
package.
SecureRandom rand = new SecureRandom(); - creates the random number
object
rand.nextInt(100) - generates random integers in the 0 to 100
range)
Using a ListItreator output the contents of the LinkedList in the original order.
Using a ListItreator output the contents of the LinkedList in the reverse order.
Note: Variable names and object names are used arbitrarily. These can be changed according to the user's choice. Please refer to code snippets for a better understanding of comments and indentations.
IDE Used: Eclipse
Program Code
import java.util.*;
import java.security.SecureRandom;
public class randomlist {
public static void main(String[] args) {
// iterator variable for inserting
25 random integer
int itr;
// create an object of linkedlist
class
LinkedList<Integer> rand_list
= new LinkedList<Integer>();
// create an object of secure
random class to generate random number
SecureRandom sec_rand = new
SecureRandom();
// generate secure random number of
range 0 to 100 and insert in the linked list
for(itr= 0; itr < 25;
itr++)
{
rand_list.add(sec_rand.nextInt(100));
}
// output the content of the linked
list in original order using iterator
System.out.println("Content of
LinkedList in original order");
Iterator<Integer>
o_itr=rand_list.iterator();
while(o_itr.hasNext())
{
System.out.print(o_itr.next()+" ");
}
// output the content of the linked list in original order using
iterator
System.out.println("\n\nContent of LinkedList in reverse
order");
Iterator<Integer> r_itr=rand_list.descendingIterator();
while(r_itr.hasNext())
{
System.out.print(r_itr.next()+" ");
}
}
}
Code Snippets
Sample Output