在插入Java ArrayList之前先搜索它
我有一个ArrayList,它存储了多个具有3个值的对象:在插入Java ArrayList之前先搜索它,java,search,arraylist,Java,Search,Arraylist,我有一个ArrayList,它存储了多个具有3个值的对象:title、fileName、tuthor。在将对象添加到ArrayList之前,我想检查fileName的值是否已经存在 PhotographArrayList photos = new PhotographArrayList(); Photograph photo; photo = new Photograph(); photo.submitPhotograph("Enter photograph details: \n"); i
title、fileName、tuthor
。在将对象添加到ArrayList之前,我想检查fileName的值是否已经存在
PhotographArrayList photos = new PhotographArrayList();
Photograph photo;
photo = new Photograph();
photo.submitPhotograph("Enter photograph details: \n");
if(photos.find (photo.photoExist()) !=null)
System.out.println("\nError: File already in use\n");
else
photos.add(photo);
break;
这就是我当前检查照片文件名是否已经存在的方式,它从我的ArrayList
类调用此方法
public Photograph find(String aEmail) {
int index = id.indexOf(aEmail);
if(index == -1)
return null;
else return photos.get(index);
}
然而,这段代码可以工作,但使在系统上使用Junit测试变得很困难,我想找到一种方法,在搜索ArrayList
是否已经有值时,获得true
/false
答案
抱歉,如果我的Java知识有限,很难理解
我的arrayList类是:
public class PhotographArrayList {
ArrayList<Photograph> photos;
ArrayList<String> id;
public PhotographArrayList() {
photos = new ArrayList<Photograph>();
id = new ArrayList<String>();
}
public int getSize() {
return photos.size();
}
public void add(Photograph anPhoto) {
photos.add(anPhoto);
id.add(anPhoto.getAuthor());
}
public void print(String header) {
for (int i=0; i<photos.size(); i++)
System.out.println(photos.get(i));
}
public Photograph find(String aEmail) {
int index = id.indexOf(aEmail);
if(index == -1)
return null;
else return photos.get(index);
}
公共类照片列表{
ArrayList照片;
ArrayList id;
公共摄影HarrayList(){
照片=新的ArrayList();
id=新的ArrayList();
}
公共int getSize(){
返回照片。大小();
}
公共空间添加(照片和照片){
照片。添加(anPhoto);
id.add(anPhoto.getAuthor());
}
公共作废打印(字符串标题){
对于(int i=0;i您应该使用Arraylist
而不是创建特定的类。然后您可以覆盖photo.equals
以仅检查所需的属性,因此包含(对象)< /代码>方法可以直接进行检查。 < P>如果你想通过照片标题搜索,并希望照片列表的标题是唯一的,那么你可以考虑使用<代码> HasSET/<代码>何处-< /P>
重写photo
类的title
的equals()
方法
覆盖标题的hashCode()
方法
创建一个新的哈希集
Set photoGraphSet=new HashSet();
现在,在将任何项目添加到photoGraphSet
之前,您可以检查photoGraphSet
是否包含以下给定标题的任何照片-
Photograph aPhotograph = new Photograph("sample title");
if(!photoGraphSet.contains(aPhotograph)){
photoGraphSet.add(aPhotograph);
}
希望能有所帮助。
谢谢。什么是“您的ArrayList类”?您应该很少需要扩展ArrayList。如果您想要“真/假”答案,只需将返回类型更改为boolean
,并返回return id.indexOf(aEmail)!=-1
覆盖照片等于(和hashcode
)方法,以便使用它们与照片的另一个实例进行比较,并确定它们的内容是否“相等”或者我没有将数组列表添加到原始问题中,因为注释框太小。为什么不在不能有重复项的地方使用集合
日期。如果集合包含该项目,新项目将不会首先添加。@Darwind,假设在许多照片中
具有相同的标题,但具有不同的属性,如-宽度
,高度
。在这种情况下,如果有一次我用标题向照片集
添加一张照片e
-t
和width
10。之后,如果我想向phototgraphSet
添加另一张photographSet
,标题为title
-t
但宽度为widt
30。那么photographSet
中会保留哪个照片rted将持续存在?我不确定这就是为什么我要问,不要采取其他方式。感谢您的回答。在这种情况下,您可能也会看到链接-这是真的-可能需要添加自定义比较器以避免此问题,但现在您的检查.contains()
在您设置的场景中没有多大用处,因为如果高度或宽度与第一张照片的值不完全相同,那么它们将永远不会相同。也许我误解了您:-)设置#添加(E)
不会覆盖项目,如果它存在:-)