方法标头与参数的类型不同

时间:2018-09-01 08:45:26

标签: java

public class Album {

    private String albumtitle;
    private ArrayList<Photo> photos;

    /**
     * This constructor should initialize the
     * instance variables of the class.
     */
    public Album(String title) {

        this.albumtitle = title;
        photos = new ArrayList<>();

    }

问题在于它一直在说“ .contains有一个字符串” 当方法标题类型和参数类型相同时,此方法有效。我必须以某种方式进行转换吗?

public Photo searchByTitle(String title) {
        for(Photo photo : photos) {
            if (photo.contains(title)){
               return photo;
            }
            return null;
        }

    }

简短的问题。谢谢

编辑一些人要照相课:

public class Photo {
    // These are the instance variables/fields for the class photo.
    private String title;
    private String filename;
    private String date;

    /** 
     * This constructor initialises all the field variables
     */
    public Photo(String title, String filename, String date) {

        this.title = title; // initialise the title field variable
        this.filename = filename; //initialise the filename field variable
        this.date = date; //initialise the date field variable

    }

    /** This method returns the title of the photo.
     * 
     * @return the title
     */
    public String getTitle() {
        return this.title; 
    }

    /** This method sets the title of the photo, unless
     * the string passed is an empty string, in which
     * case it does nothing.
     * 
     * @param title the title to set
     */
    public void setTitle(String title) {
        this.title = title;
    }

    /** This method returns the filename for the photo.
     * 
     * @return the filename
     */
    public String getFilename() {
        return this.filename; 
    }

    /** This method returns the date for the photo.
     * 
     * @return the date
     */
    public String getDate() {
        return this.date; 
    }

}

很明显,我是一个初学者,并且我正尽力做到这一点。我已经花了多个小时。

2 个答案:

答案 0 :(得分:2)

为什么要检查照片中是否包含标题,标题的类型为字符串,而照片的类型为其他类型。您不应该将照片的标题与给定的标题匹配吗?

public Photo searchByTitle(String title) {
    for(Photo photo : photos) {
        if (photo.getTitle().equals(title)){
           return photo;
        }
        return null;
    }

}

答案 1 :(得分:0)

使用Streams的Java 8+方法可能类似于:

/**
 * Returns the first photo in the Album collection with the
 * specified title, or null if no Photo with the title is found.
 * @param title The title of the photo for which one should search
 * 
 */
public Photo searchByTitle(String title)
{
    Optional<Photo> foundPhoto = photos.stream()
      .filter(p -> p.getTitle().equals(title))
      .findFirst();

    return foundPhoto.orElse(null);
}

此处的优点是它将更多的精力集中在所需的内容上(找到匹配的标题),而不是循环结构上。但是,它不一定是Java入门。但值得深思。