What is difference between List and Set in Java is a very popular Java collection interview questions and an important fundamental concept to remember while using Collections class in Java. Both List and Set are two of most important Collection classes Java Program use along with various Map implementation. Basic feature of List and Set are abstracted in List and Set interface in Java and then various implementation of List and Set adds specific feature on top of that e.g. ArrayList in Java is a List implementation backed by Array while LinkedList is another List implementation which works like linked list data-structure. In this Java tutorial we will see some fundamental difference between List and Set collections. Since List and Set are generified with introduction of Generics in Java5 these difference also application to List
This article is in continuation of my earlier post on Collection e.g. Difference between HashMap vs HashSet, Difference between HashMap and Hastable and Difference between Concurrent Collection and Synchronized Collection. If you haven't read them already you may find them useful.
List vs Set in Java
here are few note worthy differences between List and Set in Java. Remember that both of them are used to store objects and provides convenient API to insert, remove and retrieve elements, along with to support Iteration over collection.
2) Another significant difference between List and Set in Java is order. List is an Ordered Collection while Set is an unordered Collection. List maintains insertion order of elements, means any element which is inserted before will go on lower index than any element which is inserted after. Set in Java doesn't maintain any order. Though Set provide another alternative called SortedSet which can store Set elements in specific Sorting order defined by Comparable and Comparator methods of Objects stored in Set.
3) Set uses equals() method to check uniqueness of elements stored in Set, while SortedSet uses compareTo() method to implement natural sorting order of elements. In order for an element to behave properly in Set and SortedSet, equals and compareTo must be consistent to each other.
When to use List and Set in Java
Difference between LinkedList and ArrayList in Java
Difference between ArrayList and Vector in Java
Difference between throw and throws in Java
Difference between transient and volatile variable in Java
Difference between instance and local variable in Java
Difference between start and run method of Thread
No comments:
Post a Comment