在插入之前搜索Java ArrayList

时间:2015-03-23 21:07:24

标签: java search arraylist

我有一个存储多个具有3个值的对象的ArrayList: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测试,我想在搜索true时找到一种获得false / ArrayList答案的方法有价值。

很抱歉,如果我很难理解我的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);
    }

2 个答案:

答案 0 :(得分:1)

您应该使用Arraylist<Photograph>而不是创建特定的类。然后,您可以覆盖Photograph.equals以仅检查所需的属性,因此contains(Object)方法可以直接进行检查。

答案 1 :(得分:0)

如果您想按照照片标题进行搜索,并希望照片列表按照标题唯一,那么您可以考虑使用HashSet其中 -

  1. 覆盖equals()title的{​​{1}}方法。
  2. 覆盖Photograph
  3. hashCode()方法
  4. 克里特照片的新title,如 -

    HashSet

  5. 现在,在向Set<Photograph> photoGraphSet = new HashSet<PhotoGraph>();添加任何项目之前,您可以检查photoGraphSet是否包含任何给定标题的照片 -

    photoGraphSet

    希望它会有所帮助。
    感谢。

相关问题