我有一个二维的arraylist
List<List<String>> movies_info = new ArrayList<>();
我填充创建新行
movies_info.add(new ArrayList<String>());
并添加元素
movies_info.get(i).add(title);
。 我希望能够检查我添加的元素是否已存在于整个ArrayList中。是否可以在不使用以下for.loop的情况下实现此结果?
boolean found = false;
for (int i = 0; i < movies_info.size(); i++) {
if(movies_info.get(i).contain(title)) {
found = true;
}
if (!found) {
movies_info.add(new ArrayList<String>());
movies_info.get(i).add(title);
}
答案 0 :(得分:1)
您可以用HashMap替换第二个ArrayList
并检查它是否已存在。
movies_info.add(new HashMap<String,String>());
if (!movies_info.get(i).containsKey(title)){
movies_info.get(i).put(title,title);
}
在HashMap
中搜索关键字以及添加新元素都具有恒定的时间复杂度O(1)
要获得之后的值,您可以使用此代码
for (String title : movie_info.get(i).keySet()){
// Use title
}
答案 1 :(得分:1)
I would suggest a different approach. Instead of creating a list of lists of String
-s, you can have a class called Movie
and create a list of Movie
objects. Then you can directly query the list by calling the contains
method.
Note: you need to override two methods in the Movie
class, hashCode
and equals
, for the contains
method to work. By overriding these two methods, you will tell the list
object how to compare two Movie
objects.
UPDATE: you don't have to manually write the equals
and hashCode
methods (at least not if you are using the Eclipse IDE). You can just right-click anywhere inside the class's body and choose Source -> Generate hashCode and equals ...
, it will prompt you on which fields of the class you want to compare two objects, select the fields, hit OK and off you go, these two methods will be automatically generated for you.
Here's a simple example:
public class Movie
{
String title;
public Movie(String t)
{
this.title = t;
}
public String getTitle()
{
return title;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Movie other = (Movie) obj;
if (title == null)
{
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
}
You can test it like this:
import java.util.ArrayList;
import java.util.List;
public class Test
{
public static void main(String[] args)
{
List<Movie> movies = new ArrayList<Movie>();
movies.add(new Movie("Movie 1"));
movies.add(new Movie("Movie 2"));
System.out.println(movies.contains(new Movie("Movie 1")));
}
}
答案 2 :(得分:0)
这样的东西?它简化了一点..
for(List<String> mInfo : movies_info) {
if(!mInfo.contains(title)) {
//do stuff
}
}