In Java, both List and Set are interfaces in the Java Collections Framework. They both represent a collection of objects, but they have some key differences.
Order: A List is an ordered collection, meaning that the order of the elements in the List is determined by their position in the List. A Set, on the other hand, is an unordered collection, meaning that the order of the elements in the Set is not defined.
Duplicates: A List allows duplicates, meaning that the same element can appear multiple times in the List. A Set, on the other hand, does not allow duplicates, meaning that each element in the Set must be unique.
Here’s an example of how to use a List and a Set in Java:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Example {
public static void main(String[] args) {
// create a list
List<String> myList = new ArrayList<>();
myList.add("apple");
myList.add("banana");
myList.add("orange");
myList.add("banana");
// create a set
Set<String> mySet = new HashSet<>();
mySet.add("apple");
mySet.add("banana");
mySet.add("orange");
mySet.add("banana");
// print out the contents of the collections
System.out.println("List: " + myList);
System.out.println("Set: " + mySet);
}
}
In this example, we create a List called "myList" and add some strings to it, including a duplicate of the string "banana". We then create a Set called "mySet" and add the same strings to it, including a duplicate of the string "banana". Finally, we print out the contents of both collections using the "println" method.
The output of this program would be:
List: [apple, banana, orange, banana]
Set: [orange, apple, banana]
As you can see, the List contains the duplicate element "banana", while the Set does not. Additionally, the order of the elements in the List is preserved, while the order of the elements in the Set is not defined.