gpt4 book ai didi

java - 在 Java 中,检查列表是否包含另一个列表中的项目的最快方法是什么,两个列表是否属于同一类型?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:42:19 25 4
gpt4 key购买 nike

假设我有一个名为 MyClass 的类,如下所示:

public class MyClass
{
//Identifier is alpha-numeric. If the identifier starts will 'ZZ'
//is special special identifier.
private String identifier = null;
//Date string format YYYY-MM-DD
private String dateString = null;
//Just a flag (not important for this scenario)
private boolean isCoolCat = false;
//Default Constructor and getters/setters implemented
//Overrides the standard Java equals() method.
//This way, when ArrayList calls contains() for MyClass objects
//it will only check the Date (for ZZ identifier)
//and identifier values against each other instead of
//also comparing the isCoolCat indicator value.
@Override
public boolean equals(Object obj)
{
if(this == obj)
{
return true;
}
if(obj == null)
{
return false;
}
if(getClass() != obj.getClass())
{
return false;
}
MyClass other = (MyClass) obj;
if(this.identifier == null)
{
if(other.identifier != null)
{
return false;
}
} else if(!this.identifier.equals(other.identifier)) {
return false;
}
if(other.identifier.startsWith("ZZ"))
{
if(!this.dateString.equals(other.dateString))
{
return false;
}
}
return true;
}
}

在另一个类中,我有两个 MyClass 类型的列表,每个包含 100,000 个对象。我需要检查一个列表中的项目是否在另一个列表中,我目前按如下方式完成此操作:

`

List<MyClass> inList = new ArrayList<MyClass>();
List<MyClass> outList = new ArrayList<MyClass>();
inList = someMethodForIn();
outList = someMethodForOut();
//For loop iterates through inList and check if outList contains
//MyClass object from inList if it doesn't then it adds it.
for(MyClass inObj : inList)
{
if(!outList.contains(inObj))
{
outList.add(inObj);
}
}

我的问题是:这是完成此任务的最快方法吗?如果不能,你能告诉我一个更好的实现来提高性能吗?列表大小并不总是 100,000。目前在我的平台上,100,000 个大小大约需要 2 分钟。假设它可以在 1 到 1,000,000 之间变化。

最佳答案

您想使用 Set 为了这。 Set 有一个 contains 可以在 O(1) 时间内确定对象是否在集合中的方法。

List<MyClass> 转换时需要注意的几件事至 Set<MyClass> :

  1. 您将丢失元素的顺序
  2. 你将丢失重复的元素
  3. 你的 MyClass需要实现hashcode()equals() , 和 they should be consistent .

转换您的 ListSet你可以只使用:

Set<MyObject> s1 = new HashSet<>(inList);
Set<MyObject> s2 = new HashSet<>(outList);

Java doc解释了如何求两个集合的并集、交集和差集。特别是,您似乎对联盟感兴趣:

// transforms s2 into the union of s1 and s2. (The union of two sets 
// is the set containing all of the elements contained in either set.)
s2.addAll(s1)

关于java - 在 Java 中,检查列表是否包含另一个列表中的项目的最快方法是什么,两个列表是否属于同一类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31846205/

25 4 0