LinkedHashSet Preserves Insertion Order

Deduplicate while keeping first-seen order: HashSet scrambles iteration, LinkedHashSet remembers insertion, and re-adding an element never moves it.

JavaData Integrity

Code

snippet
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

public class VisitOrder {

    public static void main(String[] args) {
        String[] visits = {"paris", "oslo", "tokyo", "oslo", "paris", "lima"};

        // HashSet 只保证去重:遍历顺序由哈希桶决定,不可预测
        Set<String> unique = new HashSet<>(Arrays.asList(visits));
        System.out.println("HashSet: " + unique);

        // LinkedHashSet 额外用链表记录插入顺序:去重且保持首次出现次序
        Set<String> ordered = new LinkedHashSet<>();
        for (String city : visits) {
            ordered.add(city); // 重复元素 add 返回 false,位置不会刷新
        }
        System.out.println("LinkedHashSet: " + ordered);

        // 重复添加不会把元素挪到尾部
        boolean reAdded = ordered.add("oslo");
        System.out.println("re-add accepted: " + reAdded);
        System.out.println("after re-add: " + ordered);
        System.out.println("size: " + ordered.size());
    }
}

How it works

Structurally, expect the class VisitOrder and the function main and nothing else.

Iteration happens inside for (String city : visits) — everything outside it runs once.

Putting it to use

Running the file prints labeled results such as HashSet:, LinkedHashSet:, re-add accepted: — each operation’s effect is visible in the output.

Core lines

String[] visits = {"paris", "oslo", "tokyo", "oslo", "paris", "lima"};
Set<String> unique = new HashSet<>(Arrays.asList(visits));
ordered.add(city); // 重复元素 add 返回 false,位置不会刷新
}

Interactive Tools for This Topic

FAQ

What does LinkedHashSet Preserves Insertion Order print when run?
No setup needed: run the file and look for labeled lines like `HashSet:`, `LinkedHashSet:`, `re-add accepted:` in the output.