我需要针对遇到的一个问题的优化解决方案:
有一个具有一些字段的对象A:
class A{
String city;
String state;
String phoneNo;
-
-
-
-
}
还有另一个对象Bi.e列表:
class B{
String name;
int id;
List<C> Objects;
}
Class C{
// having similar member variable as in A
String city;
String state;
String phone;
-
-
-
-
}
现在,问题是我要遍历对象B的列表并获取对象C的列表,并将这些详细信息与对象A进行比较。
我脑海中的基本O(n ^ 2)解决方案是:
for(B b : List of b){
List<C> objects= b.getObjects()
for(C c : objects){
if(c.getState.equalsIgnoreCase(A.getState)){
}
.... similar condition to apply ...
}
}
最后,我需要B对象的所有List都与A成员变量配对,并且我想主要是在时间和空间上减少复杂性。
对于初学者,您可以使C类扩展A类。
class A {
String city;
String state;
String phone;
// other fields of class A
boolean customEquals(A other) {
// here you can compare fields specific for class A
}
}
class C extends A {
// fields specific for class C
}
然后在循环中比较对象时使用customEquals
方法:
for (B b : bs) {
List<C> cs = b.getCs();
for (C c : cs) {
if(a.customEquals(c)) {
// do what you want to do with c
}
}
}