Generics, Collections, and Core Data Structures

Choosing the Right Collection

ReadingPreview

আপনি একটি free preview lesson দেখছেন।

Lesson Overview

Java-তে collection নির্বাচন শুধু syntax-এর বিষয় নয়।

Wrong collection বেছে নিলে code:

  • Unnecessary duplicate validation করতে পারে
  • Repeated linear search করতে পারে
  • Important ordering হারাতে পারে
  • Unsupported index logic তৈরি করতে পারে
  • Multiple structures synchronize করতে বাধ্য হতে পারে
  • Domain meaning অস্পষ্ট করতে পারে

Common collection abstractions:

List → Ordered sequence
Set  → Unique membership
Map  → Key-value lookup

কিন্তু decision এখানেই শেষ নয়।

প্রতিটি abstraction-এর multiple implementations আছে:

ArrayList
HashSet
LinkedHashSet
TreeSet
HashMap
LinkedHashMap
TreeMap

এই lesson-এ আমরা collection নির্বাচন করব requirements থেকে, habit থেকে নয়।


Learning Objectives

এই lesson শেষে আপনি পারবেন:

  • List, Set, এবং Map-এর মধ্যে deliberate choice নিতে
  • Order, uniqueness এবং lookup requirement identify করতে
  • Appropriate implementation select করতে
  • HashSet এবং LinkedHashSet distinguish করতে
  • HashMap এবং LinkedHashMap distinguish করতে
  • Sorted collections কখন useful বুঝতে
  • Basic performance trade-offs explain করতে
  • Premature optimization avoid করতে
  • Requirements পরিবর্তিত হলে collection refactor করতে

Start with the Domain Question

Collection নির্বাচন করার আগে জিজ্ঞেস করুন:

Data কী represent করছে?

Examples:

Course lesson sequence
User roles
Course lookup by code
Learner activity history
Completed lesson IDs
Country code lookup

Collection type data-এর meaning communicate করা উচিত।


Three Primary Questions

Collection বেছে নেওয়ার সময় প্রথমে তিনটি প্রশ্ন করুন।

Question 1: Does Order Matter?

First lesson
Second lesson
Third lesson

Order meaningful হলে List বা ordered implementation প্রয়োজন।

Question 2: Are Duplicates Meaningful?

Same role twice
Same completed lesson ID twice

Duplicate meaningless হলে Set useful।

Question 3: Is Lookup by a Key the Main Operation?

Course code → Course
Learner ID → Learner

Unique key lookup primary হলে Map useful।


List: Ordered Sequence

Use List when:

  • Order matters
  • Position matters
  • Duplicates may be meaningful
  • Index access useful
  • Data represents a sequence

Examples:

Course lessons
Playlist tracks
Quiz questions
Activity history
Workflow steps

Example:

List<Lesson> lessons =
        new ArrayList<>();

Why Course Lessons Usually Use List

Course lesson sequence:

1. Introduction
2. Variables
3. Classes
4. Inheritance

Requirements:

  • Order matters
  • Reordering possible
  • Position display useful
  • Same title may theoretically appear more than once
  • Duplicate ID can be separately rejected

Therefore:

List<Lesson>

is a natural model।


Set: Unique Membership

Use Set when:

  • Duplicate values have no meaning
  • Membership check is important
  • Index access unnecessary
  • Order is irrelevant or separately specified

Examples:

User roles
Completed lesson IDs
Supported languages
Unique tags
Feature permissions
Enrollment keys

Example:

Set<String> roles =
        new HashSet<>();

Why User Roles Usually Use Set

A user having:

INSTRUCTOR
INSTRUCTOR

does not provide additional meaning।

The question is:

Does the user have the INSTRUCTOR role?

Not:

At which index is the INSTRUCTOR role?

Therefore:

Set<Role>

communicates the domain better than:

List<Role>

Map: Key-Based Lookup

Use Map when:

  • Each value has a unique lookup key
  • Direct key access is common
  • Key-value relationship is meaningful
  • Repeated scanning should be avoided

Examples:

CourseCode → Course
LearnerId → Learner
CountryCode → Country
LessonId → Lesson
ConfigurationKey → Value

Example:

Map<CourseCode, Course> coursesByCode =
        new HashMap<>();

Why Course Lookup by Code Uses Map

With a list:

for (
        Course course
        : courses
) {
    if (
            course.getCode()
                    .equals(
                            expectedCode
                    )
    ) {
        return course;
    }
}

With a map:

return coursesByCode.get(
        expectedCode
);

The map directly expresses:

Find Course using CourseCode

Decision Table

RequirementBest Starting Choice
Ordered sequenceList
Position/index accessList
Duplicate occurrences meaningfulList
Unique membershipSet
Fast membership-focused lookupSet
Unique key to valueMap
Lookup by ID or codeMap
Order and unique membershipLinkedHashSet
Key lookup and insertion orderLinkedHashMap
Unique sorted valuesTreeSet
Sorted keysTreeMap

Choosing a List Implementation

The most common mutable List implementation:

ArrayList
List<Lesson> lessons =
        new ArrayList<>();

Use ArrayList as a strong default when:

  • Ordered mutable data প্রয়োজন
  • Appending common
  • Iteration common
  • Index-based reading useful
  • Frequent insertion at the beginning is not the primary operation

ArrayList Mental Model

ArrayList internally resizable array-style storage ব্যবহার করে।

Practical behavior:

  • Reading by index is efficient
  • Appending is usually efficient
  • Iteration is efficient
  • Middle insertion/removal shifts following elements

Example:

[A, B, C, D]

Remove B:

[A, C, D]

C এবং D shift করে।


Should You Avoid ArrayList Because Removal Shifts?

Usually no।

If course has:

20 lessons

middle removal cost is unlikely to matter।

Do not complicate design for theoretical performance without realistic scale।

Choose based on:

  • Data size
  • Operation frequency
  • Readability
  • Actual measurement

A Note on LinkedList

Java also provides:

LinkedList

But it should not be automatically chosen for frequent insertion/removal।

Why?

  • Finding a position may require traversal
  • Index access is weaker
  • Higher per-element memory overhead
  • Real-world locality often favors ArrayList
  • Application code rarely manipulates known internal nodes

For most application lists:

ArrayList

remains the better starting choice।

Use LinkedList only when its specific queue/deque behavior or traversal model genuinely matches requirements।


Choosing a Set Implementation

Common options:

HashSet
LinkedHashSet
TreeSet

Selection depends mainly on ordering needs।


HashSet

Use:

Set<String> roles =
        new HashSet<>();

when:

  • Uniqueness matters
  • Membership lookup matters
  • Iteration order does not matter

Characteristics:

  • No ordering guarantee
  • Uses hashCode() and equals()
  • Common default mutable set

LinkedHashSet

Use:

Set<String> tags =
        new LinkedHashSet<>();

when:

  • Uniqueness matters
  • Insertion order also matters

Example:

Instructor adds tags:

java
backend
spring

Display should preserve this order।

A HashSet cannot promise it।

A LinkedHashSet can।


TreeSet

Use:

Set<String> languageCodes =
        new TreeSet<>();

when:

  • Unique values required
  • Values must remain sorted
  • Elements have a valid ordering

Example:

ET
BN
EN

Iteration may produce:

BN
EN
ET

TreeSet Requires Ordering

Elements must either:

  • Implement Comparable
  • Or use a supplied Comparator

For strings and numbers, natural ordering already exists।

For custom objects, ordering must be designed carefully।

Example questions:

Sort Course by code?
Title?
Price?
Creation date?

There is rarely one universally correct natural order for a complex entity।


Do Not Use TreeSet Only to Sort Output Once

Suppose data normally needs hash-based membership, but one report needs alphabetical output।

You do not necessarily need to store everything permanently in a TreeSet

Possible approach:

List<String> sortedRoles =
        new ArrayList<>(
                roles
        );

sortedRoles.sort(
        String::compareTo
);

Sorting will be covered later।

Storage structure and presentation order can be separate decisions।


Choosing a Map Implementation

Common options:

HashMap
LinkedHashMap
TreeMap

Again, ordering is the main distinction।


HashMap

Use:

Map<CourseCode, Course> coursesByCode =
        new HashMap<>();

when:

  • Key lookup matters
  • Iteration order does not matter

It is the common default mutable map।


LinkedHashMap

Use:

Map<CourseCode, Course> coursesByCode =
        new LinkedHashMap<>();

when:

  • Direct key lookup matters
  • Insertion order must be preserved

Example:

Course catalog displays courses in registration order while also supporting code lookup।


TreeMap

Use:

Map<String, Course> coursesByCode =
        new TreeMap<>();

when:

  • Key-based lookup matters
  • Keys must remain sorted

Example output:

BACKEND
JAVA-OOP
SYSTEM-DESIGN

Sorted by key।


HashMap vs LinkedHashMap

Choose HashMap when order is irrelevant।

Choose LinkedHashMap when insertion order is part of expected behavior।

Do not depend on accidental HashMap iteration order।

If tests expect a stable order, the implementation contract should explicitly support it।


LinkedHashMap Can Replace a List Plus Map

Suppose requirements:

Lookup course by code
Display in registration order
Reject duplicate code

One option:

List<Course> courses;
Map<CourseCode, Course> coursesByCode;

But both structures must stay synchronized।

A simpler option:

LinkedHashMap<CourseCode, Course>

It provides:

  • Unique keys
  • Direct lookup
  • Insertion-order iteration

This may eliminate redundant state।


When a List Plus Map Is Still Needed

Sometimes order can change independently of insertion order।

Example:

Course lessons can be manually reordered
Lessons also require direct lookup by ID

Possible structures:

List<Long> lessonOrder;
Map<Long, Lesson> lessonsById;

This provides:

  • Explicit reorderable ID sequence
  • Direct lesson lookup

But every add/remove must update both structures consistently।

Use this only when the benefit justifies complexity।


Order Has Multiple Meanings

“Ordered” can mean different things:

Insertion order
Manual business order
Sorted order
Chronological order
Priority order

Choose structure based on the actual meaning।

Examples:

Insertion Order

LinkedHashSet
LinkedHashMap

Sorted Order

TreeSet
TreeMap

Manual Reorderable Sequence

List

Do not treat all ordering requirements as the same।


Duplicate Semantics Matter

Ask:

What does a duplicate mean in this domain?

Activity History

LOGIN
LOGIN
LOGIN

Duplicates are meaningful events।

Use:

List<Activity>

User Permissions

COURSE_EDIT
COURSE_EDIT

Duplicate adds no meaning।

Use:

Set<Permission>

Course Code Registry

Duplicate key should conflict or replace।

Use:

Map<CourseCode, Course>

with deliberate registration behavior।


A Set Does Not Always Replace Duplicate Validation

Suppose lessons need:

  • Ordered sequence
  • Duplicate lesson IDs forbidden

Using Set<Lesson> may lose clear manual ordering or depend on full-object equality।

Better:

List<Lesson>

and validate duplicate IDs।

Collection choice should preserve all important requirements, not only one।


Equality Requirements

Hash-based structures require correct equality semantics।

HashSet
HashMap keys
LinkedHashSet
LinkedHashMap keys

depend on:

equals()
hashCode()

Custom values used as set elements or map keys should have:

  • Stable equality
  • Compatible hash code
  • Preferably immutable equality-relevant fields

Sorted Collection Requirements

Sorted structures require comparison consistency।

TreeSet
TreeMap

use ordering to determine position and often uniqueness।

If comparison says two objects are equal:

compare(first, second) == 0

the structure may treat them as the same sorted key/element even if equals() differs।

This is an advanced but important warning:

Sorting equality and object equality should be designed consistently where possible.


Mutability Choice

You also need to choose whether the collection should be mutable।

Mutable

new ArrayList<>()
new HashSet<>()
new HashMap<>()

Use when application needs controlled add/remove/update।

Immutable Factory

List.of(...)
Set.of(...)
Map.of(...)

Use for fixed values।

Immutable Snapshot

List.copyOf(...)
Set.copyOf(...)
Map.copyOf(...)

Use when exposing current state safely।


Example: Supported Course Languages

Fixed application configuration:

Set<String> supportedLanguages =
        Set.of(
                "BN",
                "EN"
        );

No mutation required।

An immutable set is appropriate।


Example: Instructor Editing Lessons

List<Lesson> lessons =
        new ArrayList<>();

Mutation required:

  • Add
  • Remove
  • Rename
  • Reorder

Mutable list appropriate internally।

Public getter may return:

List.copyOf(
        lessons
)

Example: Course Catalog Snapshot

Internal:

Map<CourseCode, Course> coursesByCode =
        new LinkedHashMap<>();

External read:

return Map.copyOf(
        coursesByCode
);

Internal structure mutable, external snapshot immutable।


Basic Performance Mental Model

You do not need to memorize every implementation detail।

Use this practical mental model.

OperationArrayListHashSetHashMap
Append elementUsually efficientN/AN/A
Read by indexStrongUnsupportedUnsupported
Membership lookupLinear scanUsually efficientKey-based
Lookup by keyNot naturalNo associated valueUsually efficient
Preserve insertion orderYesNoNo
Allow duplicatesYesNoKeys: No
Manual reorderingStrongWeakDepends on representation

These are general expectations, not absolute runtime promises।


Complexity Terms: A Light Introduction

You may see:

O(1)
O(n)
O(log n)

Beginner mental model:

O(1)

Work does not grow proportionally with collection size in the typical model।

Example:

arrayList.get(
        index
);

O(n)

May inspect many or all elements।

Example:

list.contains(
        value
);

O(log n)

Work grows slowly as sorted structure size grows।

Commonly associated with tree-based lookup।

These describe growth patterns, not exact execution time।


Why Big-O Is Not the Only Decision

A theoretically faster structure may still be the wrong model।

Example:

Map<Integer, Lesson>

for a simple ordered lesson sequence may make code less clear than:

List<Lesson>

Even if map lookup sounds faster।

Consider:

  • Typical data size
  • Operation frequency
  • Memory cost
  • Equality complexity
  • Ordering needs
  • Maintainability
  • Domain clarity

Premature Optimization

Weak reasoning:

Map lookup is faster, so every collection should be a Map.

Problems:

  • Requires a key even when none is meaningful
  • Loses natural sequence
  • May create synchronization complexity
  • Makes APIs less intuitive
  • Optimizes operations that are not bottlenecks

Better:

  1. Choose the clearest correct model
  2. Measure realistic behavior
  3. Refactor if scale or usage requires it

Small Collections Change the Trade-Off

A course may have:

10–100 lessons

Linear lookup through a list is often perfectly acceptable।

A system-wide learner registry may have:

Millions of learners

Repeated lookup by ID naturally needs indexed persistence or map-like access।

Scale matters।


Read Frequency vs Write Frequency

Ask:

How often do we read?
How often do we add?
How often do we remove?
How often do we reorder?

Example:

Course Lessons

  • Read frequently
  • Add while drafting
  • Reorder occasionally
  • Count small

ArrayList fits well।

Completed Lesson IDs

  • Membership checked often
  • Duplicate meaningless
  • Order usually irrelevant

HashSet fits well।

Courses by Code

  • Lookup frequent
  • Code unique
  • Ordering possibly registration-based

HashMap or LinkedHashMap fits well।


Memory Also Matters

A List stores element references।

A hash-based structure also stores hash-related organizational data।

A map stores keys and values।

Maintaining both list and map duplicates references and structure overhead।

For small applications, clarity dominates।

For large data, memory profile may matter and should be measured।


Refactoring When Requirements Change

Collection choice does not have to be permanent।

Start:

List<Course> courses

Later requirement:

Frequent lookup by unique course code

Refactor to:

Map<CourseCode, Course> coursesByCode

If registration order also matters:

LinkedHashMap<CourseCode, Course>

Design should evolve with evidence।


Example Refactor: List to Map

Initial:

public final class CourseCatalog {

    private final List<Course> courses =
            new ArrayList<>();

    public Course findByCode(
            CourseCode code
    ) {
        for (
                Course course
                : courses
        ) {
            if (
                    course.getCode()
                            .equals(
                                    code
                            )
            ) {
                return course;
            }
        }

        return null;
    }
}

Refactored:

public final class CourseCatalog {

    private final Map<CourseCode, Course> coursesByCode =
            new LinkedHashMap<>();

    public Course findByCode(
            CourseCode code
    ) {
        return coursesByCode.get(
                code
        );
    }
}

Registration:

public boolean register(
        Course course
) {
    if (course == null) {
        return false;
    }

    return coursesByCode.putIfAbsent(
            course.getCode(),
            course
    ) == null;
}

Preserve Public Behavior During Refactoring

Even if internal collection changes, public API can remain stable।

Before:

catalog.findByCode(
        code
);

After:

catalog.findByCode(
        code
);

Caller does not need to know whether storage is:

List
Map
Database
Remote service

Encapsulation makes implementation changes easier।


Example Decision 1: Course Lessons

Requirements:

  • Ordered
  • Reorderable
  • Duplicate IDs rejected
  • Usually fewer than 100
  • Access by index sometimes useful

Choice:

ArrayList<Lesson>

with domain duplicate validation।


Example Decision 2: Completed Lesson IDs

Requirements:

  • Unique
  • Membership check frequent
  • Order irrelevant
  • No associated value

Choice:

HashSet<Long>

Example Decision 3: User Roles in Display Order

Requirements:

  • Unique roles
  • Display in assignment order
  • No index-based updates required

Choice:

LinkedHashSet<Role>

Example Decision 4: Course Catalog by Code

Requirements:

  • Unique course code
  • Direct lookup
  • Registration order display

Choice:

LinkedHashMap<CourseCode, Course>

Example Decision 5: Countries Sorted by Code

Requirements:

  • Unique country code
  • Associated country data
  • Sorted output by code

Choice:

TreeMap<String, Country>

If sorting only needed occasionally, a HashMap plus sorted presentation may also be appropriate।


Example Decision 6: Learner Activity Log

Requirements:

  • Chronological order
  • Repeated activity types allowed
  • Every occurrence meaningful

Choice:

List<Activity>

Usually an ArrayList for in-memory representation।

In production, long histories may belong in persistent storage rather than one unbounded in-memory list।


Bounded Collections

Some owned collections need limits।

Example:

Keep only the last 100 notifications

A list can enforce:

notifications.add(
        notification
);

if (
        notifications.size()
        > 100
) {
    notifications.remove(
            0
    );
}

But frequent removal from index 0 in large ArrayList shifts elements।

For queue-like behavior, Deque may be more appropriate।

Queues and deques are outside this lesson’s main scope, but this shows why operation patterns matter।


Collection Type in Method Parameters

Accept the abstraction the method needs।

If method only iterates:

public void printCourses(
        Collection<Course> courses
)

could accept lists and sets।

But if order is required:

public void printCourseSequence(
        List<Course> courses
)

communicates that requirement।

If unique membership is required:

public void assignRoles(
        Set<Role> roles
)

Choose parameter type based on semantic requirement, not maximum generality।


Do Not Generalize Without Benefit

Weak:

public void process(
        Iterable<Course> courses
)

This is flexible, but caller and method lose useful operations like:

size()
contains()
get()

Use broader abstraction only when the method genuinely needs less।


Collection Type in Return Values

Return type should communicate guarantees।

List<Lesson>

communicates sequence।

Set<Role>

communicates uniqueness।

Map<CourseCode, Course>

communicates key lookup।

Returning:

Collection<Course>

may hide order or uniqueness guarantees that callers need।


Avoid Returning Concrete Implementations

Prefer:

public List<Lesson> getLessons()

over:

public ArrayList<Lesson> getLessons()

Prefer:

public Set<Role> getRoles()

over:

public HashSet<Role> getRoles()

Public contract usually should expose behavior abstraction, not implementation।


Common Mistakes

Using List for Unique Membership

Leads to repeated manual duplicate checks when order is irrelevant।


Using Set for a Meaningful Sequence

Loses position semantics or relies on implementation-specific order।


Using Map Without a Meaningful Key

Creates artificial identifiers and complicates APIs।


Depending on HashSet or HashMap Iteration Order

Order is not guaranteed।


Choosing TreeSet or TreeMap Only for One Sorted Display

Permanent sorted storage may be unnecessary।


Maintaining List and Map Without Controlled Synchronization

Structures can diverge।


Choosing Collection Only by Big-O

Domain meaning and typical scale may matter more।


Exposing Concrete Collection Types

Makes implementation replacement harder।


Using Mutable Objects as Hash Keys

Lookup may break after mutation।


Ignoring Equality Rules

Set uniqueness and map key behavior become incorrect।


Over-Optimizing Small Collections

Adds complexity without meaningful benefit।


Using One Collection for Conflicting Requirements

Sometimes requirements require a composed model or a different structure।


Complete Decision Example

Suppose LiveKlass needs:

Course lesson order
Unique tags in instructor-selected order
Course lookup by code
Completed lesson membership
Learner activity history

Possible model:

public final class LearningData {

    private final List<Lesson> lessons;

    private final Set<String> tags;

    private final Map<CourseCode, Course> coursesByCode;

    private final Set<Long> completedLessonIds;

    private final List<Activity> activities;

    public LearningData() {
        this.lessons =
                new ArrayList<>();

        this.tags =
                new LinkedHashSet<>();

        this.coursesByCode =
                new LinkedHashMap<>();

        this.completedLessonIds =
                new HashSet<>();

        this.activities =
                new ArrayList<>();
    }
}

Each collection models a different domain relationship।


Why These Choices?

Lessons

ArrayList

because order and reordering matter।

Tags

LinkedHashSet

because uniqueness and insertion order matter।

Courses by Code

LinkedHashMap

because key lookup and registration order matter।

Completed Lesson IDs

HashSet

because membership matters and order does not।

Activities

ArrayList

because repeated chronological events matter।


Practice Exercises

Exercise 1: Choose the Collection

Choose the best starting type and implementation:

  1. Ordered quiz questions
  2. Unique learner roles
  3. Product code to product
  4. Unique tags preserving insertion order
  5. Country code to country sorted by code
  6. Repeated login history
  7. Completed course IDs
  8. Courses by code preserving registration order

Explain each answer।


Exercise 2: Refactor a Role List

Current:

List<String> roles =
        new ArrayList<>();

Requirements:

  • Duplicate roles invalid
  • Order irrelevant
  • Frequent membership checks

Refactor to an appropriate collection।


Exercise 3: Refactor Course Lookup

Current:

List<Course> courses

Every request searches by CourseCode

Requirements:

  • Codes unique
  • Registration order displayed
  • Direct lookup frequent

Choose and implement a better structure।


Exercise 4: Avoid Redundant Structures

A class stores:

List<Course> courses
Map<CourseCode, Course> coursesByCode

Registration order is the only ordering requirement।

Refactor to one collection if possible।


Exercise 5: Order Meaning

For each requirement, choose manual list order, insertion order, or sorted order:

  1. Course curriculum
  2. Recently assigned roles
  3. Country codes alphabetically
  4. Instructor-defined roadmap
  5. Audit events by occurrence

Exercise 6: Parameter Types

Choose the best parameter type:

List<Course>
Set<Role>
Map<CourseCode, Course>
Collection<Course>

For:

  1. Print ordered curriculum
  2. Check required roles
  3. Find course by code
  4. Count courses where order and uniqueness do not matter

Exercise 7: Refactoring Trigger

Explain when you would refactor:

List<Lesson>

to a more complex order-plus-lookup structure।

Include:

  • Expected collection size
  • Lookup frequency
  • Reordering needs
  • Complexity cost

Predict the Result

Question 1

Set<String> roles =
        new HashSet<>();

roles.add(
        "INSTRUCTOR"
);

roles.add(
        "INSTRUCTOR"
);

System.out.println(
        roles.size()
);

Answer

1

Question 2

Map<String, String> courses =
        new HashMap<>();

courses.put(
        "JAVA",
        "First"
);

courses.put(
        "JAVA",
        "Second"
);

System.out.println(
        courses.size()
);

System.out.println(
        courses.get(
                "JAVA"
        )
);

Answer

1
Second

Equal key replaces the previous value।


Question 3

Set<String> tags =
        new LinkedHashSet<>();

tags.add(
        "java"
);

tags.add(
        "backend"
);

tags.add(
        "spring"
);

What iteration order is expected?

Answer

java
backend
spring

LinkedHashSet preserves insertion order।


Question 4

Map<String, Integer> values =
        new TreeMap<>();

values.put(
        "C",
        3
);

values.put(
        "A",
        1
);

values.put(
        "B",
        2
);

What key iteration order is expected?

Answer

A
B
C

Question 5

Does HashMap guarantee that entries print in insertion order?

Answer

No।

Any observed insertion-like order is accidental unless an ordered implementation is used।


Knowledge Check

Question 1

Which three questions should guide initial collection choice?

Question 2

When is List appropriate?

Question 3

When is Set appropriate?

Question 4

When is Map appropriate?

Question 5

What is the common default mutable list implementation?

Question 6

What is the difference between HashSet and LinkedHashSet?

Question 7

What is the difference between HashMap and LinkedHashMap?

Question 8

What do TreeSet and TreeMap provide?

Question 9

Why should you not depend on HashMap iteration order?

Question 10

Why might LinkedHashMap replace a list plus map?

Question 11

What is the risk of maintaining both a list and map?

Question 12

Why is Big-O not the only collection-selection factor?

Question 13

When should a collection be immutable?

Question 14

Why expose List instead of ArrayList in a public API?

Question 15

When is linear search through a list acceptable?


Knowledge Check Answers

Answer 1

Whether order matters, duplicates are meaningful, and key-based lookup is primary।

Answer 2

When sequence, position, repeated values, or manual ordering matter।

Answer 3

When unique membership matters and index access is unnecessary।

Answer 4

When values are accessed primarily through unique stable keys।

Answer 5

ArrayList

Answer 6

HashSet has no order guarantee; LinkedHashSet preserves insertion order।

Answer 7

HashMap has no order guarantee; LinkedHashMap preserves insertion order।

Answer 8

Sorted unique values and sorted keys।

Answer 9

Its contract does not promise stable or insertion-based ordering।

Answer 10

It provides unique-key lookup and insertion-order iteration in one structure।

Answer 11

Updates may affect only one structure, causing inconsistent data।

Answer 12

Domain meaning, scale, operation frequency, memory, readability, and maintenance also matter।

Answer 13

When values are fixed or when exposing a safe snapshot to callers।

Answer 14

It exposes the required abstraction and allows implementation replacement।

Answer 15

When collections are small, lookup is infrequent, and the simpler model fits the domain।


Lesson Summary

এই lesson-এ আমরা শিখেছি:

  • Collection choice domain requirements থেকে আসা উচিত
  • Order, duplicates এবং key lookup primary decision factors
  • List ordered sequence model করে
  • Set unique membership model করে
  • Map key-value lookup model করে
  • ArrayList common mutable ordered collection
  • HashSet unique unordered membership-এর default
  • LinkedHashSet uniqueness এবং insertion order combine করে
  • TreeSet sorted unique values রাখে
  • HashMap key lookup-এর common default
  • LinkedHashMap lookup এবং insertion order combine করে
  • TreeMap keys sorted রাখে
  • Manual order, insertion order এবং sorted order different concepts
  • Duplicate semantics domain-specific
  • A set does not always replace duplicate validation in an ordered model
  • Hash-based collections correct equality require করে
  • Sorted collections consistent comparison require করে
  • Mutable internal collections এবং immutable external snapshots একসঙ্গে ব্যবহার করা যায়
  • Basic performance characteristics useful, but domain clarity remains central
  • Big-O exact execution time নয়
  • Premature optimization unnecessary complexity তৈরি করতে পারে
  • Small collections often favor simple designs
  • Read/write operation patterns collection choice influence করে
  • Requirements change হলে internal collection refactor করা যায়
  • Encapsulation public API stable রাখতে সাহায্য করে
  • LinkedHashMap sometimes redundant list-plus-map design replace করতে পারে
  • Public APIs সাধারণত collection interface expose করবে, concrete implementation নয়

Next Lesson

পরবর্তী lesson:

Module Practice and Assessment

আমরা একটি complete collection-based learning platform model তৈরি করব:

  • Ordered course catalog
  • Unique course codes
  • Course lookup by code
  • Ordered modules and lessons
  • Duplicate lesson prevention
  • Learner enrollment registry
  • List, Set, এবং Map
  • Defensive copying
  • Immutable snapshots
  • Counting and grouping
  • Collection choice assessment
  • Predict-the-output
  • Final design challenge