Home Java Example Java Util Shuffling the Element of a List or Array



Shuffling the Element of a List or Array
Posted on: April 16, 2007 at 12:00 AM
In this section, you will learn about shuffling the element of a list or array.

Shuffling the Element of a List or Array

     

Shuffling is the technique i.e. used to randomize the list or array to prepare each and every element for the operation. In this section, you will learn about shuffling the element of a list or array. Shuffling the element means moving the element from one place to another place randomly.

In the given program, list is created which contains some values. List lists the elements of the Collection. This program takes some values for the list and it sorts these values after shuffling. For this purposes some methods and APIs are explained below which have been used in the program: 

List:
This is the class of java.util.*; package which extends Collection. This is used to list elements available in the Collections. In this program a argument <Integer> has been passed with the List for type checking.

ArrayList():
This is the construction of ArrayList class of the java.util.*; package that extends the AbstractList class. It constructs an empty list. You can specify the capacity of the list by passing a value to the constructor.

sort(list):
This is the method of the Collections class which is used to sort the list elements in the default order.

Here is the code of program:

import java.util.*;
import java.io.*;

public class ShufflingListAndArray{
  public static void main(String[] argsthrows IOException{
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  System.out.print("How many elements you want to add to the list: ");
  int n = Integer.parseInt(in.readLine());
  System.out.print("Enter " + n + " numbers to sort: ");
  List<Integer> list = new ArrayList<Integer>();
  for(int i = 0; i < n; i++){
  list.add(Integer.parseInt(in.readLine()));
  }
  Collections.shuffle(list);
  Collections.sort(list);
  System.out.println("List sorting :"+ list);
  }
}

Download this example

Related Tags for Shuffling the Element of a List or Array:
javacdomarraylistrandomiosedreadoperapackageelementfortoeachsheilliusepeinmntoutparjoperationpackadtechemagerandomizemeackdostechniqueatpacratiokisllprerayeaandarutilvautiufzshufflingssthavstabatiprmindonomo


More Tutorials from this section

Ask Questions?    Discuss: Shuffling the Element of a List or Array   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.