Sobes.tech
Junior — Middle

How do collections List and Set differ in structure and usage?

sobes.tech AI

Answer from AI

Collections List and Set differ in structure and behavior:

  • List — an ordered collection that stores elements in the order they are added. It allows duplicates and provides access to elements by index.
  • Set — an unordered collection that stores only unique elements (no duplicates). The order of elements is not guaranteed (depends on the specific implementation).

Example of usage:

List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("apple"); // duplicate is allowed

Set<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
set.add("apple"); // duplicate is ignored

Use List when order is important and duplicates are allowed. Use Set when unique elements are needed and order is not important.