简体   繁体   English

如何从Java中的对象数组列表中获取字符串?

[英]How to get an a String from an array list of objects in java?

I am having the user input an index. 我正在让用户输入索引。 That index will be used to find a particular object called Movie in the list array called movieList . 该索引将用于在名为movieList的列表数组中找到名为Movie的特定对象。 In that object i want to find the value of genreOfMovie and convert it to String . 在该对象中,我想找到genreOfMovie的值并将其转换为String

I am using this line of code: 我正在使用以下代码行:

Movie genreOfMovie = (Movie) movieList.get(Integer.parseInt(index) - 1);

to set the veritable to what the user is looking for. 将名副其实地设置为用户正在寻找的东西。

However when i run the program I dont get a string of a genre , what i get is some thing similar to database.Movie@71aa1ce9 . 但是,当我运行程序时,我没有得到任何类型的字符串,我得到的是类似于database.Movie@71aa1ce9东西。 Database if the name of the program and Movie is the name of the object so what is @71aa1ce9 and how do i change this like 数据库,如果程序和电影的名称是对象的名称,那么@71aa1ce9是什么,我该如何更改?

Movie genreOfMovie = (Movie) movieList.get(Integer.parseInt(index) - 1); 

of code to print some sort of string like action because that is what was stored in there. 代码来打印某种字符串,例如动作,因为这是存储在其中的内容。

      String index  = TxtSearch.getText();
      Movie genreOfMovie = (Movie) movieList.get(Integer.parseInt(index) - 1);
      int counter = 0;
      do {
          counter++;
      } while (CbxGenres.getComponent(counter) != genreOfGame.toString());

You need to override the toString() method in your Movie class. 您需要在Movie类中重写toString()方法。 Here, you can assemble a description of the object using its instance fields as well as any other String. 在这里,您可以使用对象的实例字段以及任何其他String来组合对象的描述。

public class Movie {
    private String name;
    private String genre;

    ...

    @Override
    public String toString() {
        return genre;
        // alternatively, you can concatenate data into a String and return that, e.g. return name + " (" + genre + ")"
    }
}

On a side note, why doesn't your movieList have a generic type, eg List<Movie> ? 附带说明一下,为什么movieList没有通用类型,例如List<Movie>

What you are doing is printing the String interpretation of the Movie object. 您正在做的是打印Movie对象的String解释。 What you want, is create your own string interpretation. 您想要的是创建自己的字符串解释。 You do this by overriding the toString() method in your movie object and returning the genre. 为此,您可以重写影片对象中的toString()方法并返回流派。

An example: 一个例子:

@Override
public String toString() {
   return this.genre;
} 

"@71aa1ce9" is name of object instance “ @ 71aa1ce9”是对象实例的名称

Movie genreOfMovie = (Movie)

this is instance of one movie, to get genre you probably need to call some method on movie it self .. like .getGenre() or something like that 这是一部电影的实例,要获得体裁,您可能需要自行在电影上调用某种方法。如.getGenre()或类似的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM