面试题答案
一键面试- 实现思路:
- 创建一个自定义类来表示复杂数据结构中的对象,并重写
equals
和hashCode
方法,基于特定属性来判断对象的唯一性。 - 使用
LinkedHashSet
来存储对象,LinkedHashSet
会维护插入顺序,满足按照对象首次插入的顺序进行遍历的要求。
- 创建一个自定义类来表示复杂数据结构中的对象,并重写
- 核心代码示例:
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
,通过重写equals
和hashCode
方法基于特定属性保证唯一性,并使用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
的部分功能,利用字典键的唯一性基于特定属性来保证对象的唯一性,并按照插入顺序遍历。