Post

Collection_List/ Set/ Map

✅ Collection Framework

framework to save, maange data in JAVA

Screenshot 2024-08-21 at 01 41 45

✅ List

  • duplicate element possible ⭕️
  • has order in data
  • insertion order ⭕️
  • store null ⭕️
  • has index
  • can get() element by index
  • 👍🏻 search, regularly access the element

  • ArrayList
  • LinkedList

✅ Set

  • duplicate items impossible ❌
  • has no order in data
  • insertion order ❌
  • only one null value
  • 👍🏻 build collection of distinct items

  • HashSet
  • TreeSet

When to use set, instead of list?

when all items need to be unique

✅ Map

  • key ➕ value are mapped
  • hold pairs of keys and values
  • 👍🏻 store data in key-value form
  • duplicate key impossible ❌
  • duplicate value possible ⭕️
  • insertion order ❌
  • allow single null key at most
  • allow null value ⭕️

  • HashMap
  • TreeMap
1
2
3
4
5
6
7
8
9
        // Creating object for a Map.
        Map<String, Integer> map
            = new HashMap< String, Integer>();

        // Adding Elements using Map.
        map.put( "Rajat", 101);
        map.put("Shyam", 102);
        map.put("Rahul", 103);
        map.put("Krishna", 104);

☑️ ArrayList

Screenshot 2024-08-20 at 01 15 45

  • one direction pointer
  • 👍🏻 fast in search

☑️ LinkedList

Screenshot 2024-08-20 at 01 32 20

  • double direction pointer
  • 👍🏻 fast in insertion, deletion

ArrayList 🆚 LinkedList https://soheeparklee.github.io/posts/DB-3array-list-linked/

☑️ HashSet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Instantiate an object of HashSet
HashSet<ArrayList> set = new HashSet<>();

// create ArrayList list1
ArrayList<Integer> list1 = new ArrayList<>();

// create ArrayList list2
ArrayList<Integer> list2 = new ArrayList<>();

// Add elements using add method
list1.add(1);
list1.add(2);
list2.add(1);
list2.add(2);
set.add(list1);
set.add(list2);

// print the set size to understand the
// internal storage of ArrayList in Set
System.out.println(set.size());

//result = 1
//two lists are considered equal if they have the same elements in the same order
  • creates collection that stores elements in a hash table
  • hash code, to function as object identifier
  • insertion order not guaranteed ❌
  • data duplication ❌

☑️ LinkedHashSet

  • Linked list ➕ Hash Table
  • insertion order guaranteed ⭕️(list의 특징)
  • data duplication ❌(set의 특징)

☑️ TreeSet

  • (default) if data can be compared, ordered in ascending otder
  • data duplication ❌
  • can implement comparable

☑️ HashMap

Screenshot 2024-08-20 at 12 47 18

  • insertion order not guaranteed ❌
  • key duplication imossible ❌

☑️ LinkedHashMap

  • insertion order guaranteed ⭕️
  • key duplication imossible ❌

☑️ TreeMap

  • save key-value on red-black tree
  • (default) if data can be compared, ordered in ascending otder
  • can implement comparable
This post is licensed under CC BY 4.0 by the author.