【问题标题】:Use indexOf with an ArrayList that has multiple objects将 indexOf 与具有多个对象的 ArrayList 一起使用
【发布时间】:2016-11-08 20:03:41
【问题描述】:

在下面的代码中我想使用indexOf(),但我找不到正确的方法。

电影类:

public class Movie {


    private String title;
    private String genre;
    private String actor;
    private int yearPublished;

    public Movie(String title, String genre, String actor, int yearPublished) {
        this.title = title;
        this.genre = genre;
        this.actor = actor;
        this.yearPublished = yearPublished;
    }

    @Override
    public String toString() {
        return  title + ", Genre: " + genre + ", Actor(s):" + actor + ", Year of publishing: " + yearPublished;
    }



    public String getTitle() {
        return title;
    }

    public String getGenre() {
        return genre;
    }

    public String getActor() {
        return actor;
    }

    public int getYearPublished() {
        return yearPublished;
    }


}

控制器类:

public class Controller {

    void start() {
        scanning();
        printing("Movies:");
        selectYourMovie();

    }

    private List<Movie> movies = new ArrayList<>();

    private void scanning() {
        try {
            Scanner fileScanner = new Scanner(new File("movies.txt"));

            String row;
            String []data;

            while (fileScanner.hasNextLine()) {     
                row = fileScanner.nextLine();
                data = row.split(";");
                movies.add(new Movie(data[0], data[1], data[2], Integer.parseInt(data[3])));

            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private void printing(String cim) {
        for (Movie movie : movies) {
            System.out.println(movie);
        }
    }

    private void selectYourMovie() {

        System.out.println(movies.indexOf(/*What to put here?*/);
    }

}

以及txt文件的内容:

The Matrix;action;Keanu Reeves;1999

The Lord of the Rings;fantasy;Elijah Wood;2001

Harry Potter;fantasy;Daniel Radcliffe;2001

The Notebook;drama;Ryan Gosling;2004

Step Up;drama, dance;Channing Tatum;2006

Pulp Fiction;crime;Samuel L. Jackson, John Travolta;1994

Star Wars: A New Hope;action;Mark Hamill;1977

所以我想返回给定电影的索引,但我找不到如何处理包含多个对象的列表。由于传递 txt 的整行是行不通的。

对此有何提示?

【问题讨论】:

    标签: java arraylist indexof


    【解决方案1】:

    ArraysList 在 indexOf

    方法的实现中使用 equals

    看:

     public int indexOf(Object o) {
            if (o == null) {
                for (int i = 0; i < size; i++)
                    if (elementData[i]==null)
                        return i;
            } else {
                for (int i = 0; i < size; i++)
                    if (o.equals(elementData[i]))
                        return i;
            }
            return -1;
        }
    

    所以你的电影类还没有完全开发到能够使用它...... :)

    正确覆盖等于(和 hashCode),以便代码可以工作!

    【讨论】:

      【解决方案2】:

      您当然可以使用List#indexOf(T) 方法。要以正确的方式执行此操作,请在您的电影对象中重新实现 Object#equals 方法。

      【讨论】:

        【解决方案3】:

        因为您使用的是自定义对象 [即Movies] 您可能希望覆盖其 equals() 和 hashCode() 方法,以便 indexOf() 方法可以识别给定的 Movies 对象是否与 List 中可用的任何现有 Movies 对象相同。

        您可以阅读这篇文章以了解更多信息:Java: howto write equals() shorter

        我建议使用 Apache 库中的 EqualsBuilder commons-lang3

        【讨论】:

          【解决方案4】:

          我相信你使用List#indexOf(Object)方法是错误的。

          List#indexOf(Object)

          返回指定元素第一次出现的索引 此列表,如果此列表不包含该元素,则为 -1。

          如您所见,该方法采用一个参数,Object,它必须与列表中的元素类型相同。如果您存储Movie 类型的对象,那么您必须使用List#indexOf(Movie),因为如果您使用不同类型的对象,它将始终返回-1。

          您还需要确保没有将对象添加到列表中,然后再次创建它,然后使用List#indexOf(Object)

          如果您想通过名称查找 Movie 的索引,只需使用 for()-loop 遍历列表中的所有对象并检查电影名称是否等于(忽略区分大小写)您的给定名称.然后把它还回去,瞧,你成功了。

          //编辑: 当然,您也可以覆盖 Movie 类中的 equals() 方法。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-09-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-06-26
            • 1970-01-01
            相关资源
            最近更新 更多