MST

星途 面试题库

面试题:Java LinkedHashSet插入顺序维护在复杂数据结构中的应用

假设有一个复杂的数据结构,包含多个对象,每个对象有多个属性。现在需要使用LinkedHashSet存储这些对象,并且要求按照对象首次插入的顺序进行遍历。同时,要保证对象的唯一性是基于某个特定属性判断的。请描述实现思路并给出核心代码示例。
38.6万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 实现思路
    • 创建一个自定义类来表示复杂数据结构中的对象,并重写equalshashCode方法,基于特定属性来判断对象的唯一性。
    • 使用LinkedHashSet来存储对象,LinkedHashSet会维护插入顺序,满足按照对象首次插入的顺序进行遍历的要求。
  2. 核心代码示例
import java.util.LinkedHashSet;
import java.util.Set;

class ComplexObject {
    private String specificProperty;
    // 其他属性
    private String otherProperty;

    public ComplexObject(String specificProperty, String otherProperty) {
        this.specificProperty = specificProperty;
        this.otherProperty = otherProperty;
    }

    // 基于特定属性重写equals方法
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ComplexObject that = (ComplexObject) o;
        return specificProperty.equals(that.specificProperty);
    }

    // 基于特定属性重写hashCode方法
    @Override
    public int hashCode() {
        return specificProperty.hashCode();
    }
}

public class Main {
    public static void main(String[] args) {
        Set<ComplexObject> set = new LinkedHashSet<>();
        set.add(new ComplexObject("prop1", "other1"));
        set.add(new ComplexObject("prop2", "other2"));
        set.add(new ComplexObject("prop1", "other3")); // 不会重复添加,因为specificProperty为prop1已经存在

        for (ComplexObject obj : set) {
            System.out.println("Specific Property: " + obj.specificProperty + ", Other Property: " + obj.otherProperty);
        }
    }
}

上述Java代码展示了如何创建一个自定义类ComplexObject,通过重写equalshashCode方法基于特定属性保证唯一性,并使用LinkedHashSet按照插入顺序遍历对象。如果是其他编程语言,实现思路类似,只是语法会有所不同。例如在Python中,可以使用OrderedDict来实现类似功能(但Python没有严格意义上的基于类的Set来保证唯一性,需要额外处理):

from collections import OrderedDict

class ComplexObject:
    def __init__(self, specific_property, other_property):
        self.specific_property = specific_property
        self.other_property = other_property

# 模拟LinkedHashSet功能
unique_objects = OrderedDict()
obj1 = ComplexObject("prop1", "other1")
obj2 = ComplexObject("prop2", "other2")
obj3 = ComplexObject("prop1", "other3")

unique_objects[obj1.specific_property] = obj1
unique_objects[obj2.specific_property] = obj2
unique_objects[obj3.specific_property] = obj3 # 这里会覆盖之前的obj1,因为specific_property相同

for obj in unique_objects.values():
    print(f"Specific Property: {obj.specific_property}, Other Property: {obj.other_property}")

Python代码通过OrderedDict模拟了LinkedHashSet的部分功能,利用字典键的唯一性基于特定属性来保证对象的唯一性,并按照插入顺序遍历。