InterviewSolution
| 1. |
What is meant by Ordered and Sorted in Java collections? |
|
Answer» Ordered in Java Collection An ordered collection in Java mean that the elements of the collection have a definite order. The order of the elements is unconstrained by their value. In other words, the order of the elements in the ordered collection does not depend on their value. An example for an ordered Java collection is a LIST. List in Java are interface that extend the Collection interface. Java List allows us to exercise control over the index for insertion of elements. List allows searching and access of elements by their index. Duplicate elements can be stored in a List. Instances of the list can be created by the new KEYWORD along with the ArrayList, LinkedList, Vector and Stack classes. List arrayListObj = new ArrayList(); List stackObj = new Stack(); List linkedListObj = new LinkedList(); List vectorObj = new Vector();After JDK 1.5, we can limit the type of object we want in the List, List<Obj> list = new List<Obj>();Let us see an example of a List in Java: import java.util.*; public class Example { public static void main(String[] ARGS) { List<Integer> list = new ArrayList<Integer>(); list.add(0,6); // adds element 6 at index 0 list.add(1,3); // adds element 3 at index 1 list.add(2,9); // adds element 9 at index 2 System.out.println(list); list.remove(1); // removes element at index = 1 System.out.println(list); }The OUTPUT is as follows $javac Example.java $java Example [6, 3, 9] [6, 9]Sorted in Java Collection A sorted collection in Java is a collection whose elements have a definite order and the order is constrained by the values of the elements. In other words, the order of the elements is dependent on the values of the elements. An example for a sorted collection in Java is a SORTEDSET. SortedSet is an interface which extends the Set interface in Java. All the components in SortedSet are bound to implement the Comparator interface in Java. Let us see an example of a SortedSet: import java.util.*; public class Example { public static void main(String[] args) { SortedSet set = new TreeSet(); // creating a SortedSet object set set.add(10); // adding 10 to the SortedSet set.add(1); // adding 1 to the SortedSet set.add(4); // adding 4 to the SortedSet Iterator i = set.iterator(); // creating an iterator // iterating through the SortedSet by checking for the presence of next element while (i.hasNext()) { Object obj = i.next(); // acquiring the element System.out.println(obj); } } }The output is as follows: $javac Example.java $java Example 1 4 10 |
|