用户输入2 sting,存储在变量a和b中。现在程序中存在很多ArrayList,我们要检查是否存在一个存在于变量a中的名称的ArrayList。 那我怎么能这样做呢?
public static void root(String a,String b)
{
ArrayList chicago=new ArrayList();
chicago.add("newyork");
chicago.add("new jersy");
chicago.add("dallas");
ArrayList buffalo=new ArrayList();
buffalo.add("arlington");
buffalo.add("california");
buffalo.add("dallas");
ArrayList newyork=new ArrayList();
newyork.add("chicago");
newyork.add("paris");
newyork.add("nigara");
ArrayList stations=new ArrayList();
stations.add(chicago);
stations.add(buffalo);
stations.add(newyork);
if(stations.contains(a))
{
}
}
答案 0 :(得分:1)
这应该对你有用(虽然不是最佳解决方案):
import java.util.ArrayList;
import java.util.Iterator;
public class Test2 {
public Test2() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// Test a String.
String test = "newyork";
String test2 = "dallas";
root(test, test2);
}
public static void root(String a,String b)
{
ArrayList<String> chicago=new ArrayList();
chicago.add("newyork");
chicago.add("new jersy");
chicago.add("dallas");
ArrayList<String> buffalo=new ArrayList();
buffalo.add("arlington");
buffalo.add("california");
buffalo.add("dallas");
ArrayList<String> newyork=new ArrayList();
newyork.add("chicago");
newyork.add("paris");
newyork.add("nigara");
ArrayList<ArrayList> stations=new ArrayList();
stations.add(chicago);
stations.add(buffalo);
stations.add(newyork);
// Go through each ArrayList.
Iterator<ArrayList> arrStations = stations.iterator();
while(arrStations.hasNext()){
ArrayList<String> tmp = arrStations.next();
if(tmp.contains(a)){
// a is in the ArrayList.
System.out.println("String '" + a + "', is in");
}
}
}
}
答案 1 :(得分:0)
看起来你有一个嵌套的ArrayList。如果你想查找a是否存在,你将需要遍历嵌套数组列表
public static void root(String a,String b)
{
ArrayList chicago=new ArrayList();
chicago.add("newyork");
chicago.add("new jersy");
chicago.add("dallas");
ArrayList buffalo=new ArrayList();
buffalo.add("arlington");
buffalo.add("california");
buffalo.add("dallas");
ArrayList newyork=new ArrayList();
newyork.add("chicago");
newyork.add("paris");
newyork.add("nigara");
ArrayList stations=new ArrayList();
stations.add(chicago);
stations.add(buffalo);
stations.add(newyork);
for(Object o : stations) {
//cast the object back to an arrayList
ArrayList l = (ArrayList) o;
if(l.contains(a))
{
System.out.println("Found");
break;
}else {
System.out.println("Not found");
}
}
答案 2 :(得分:-1)
使用类似HashMap<String, List<String>>
的内容。 HashMap
中的键可能是您在此处使用的字符串。
Map<String,List<String>> map = new HashMap<>();
ArrayList<String> chicago=new ArrayList<>();
chicago.add("newyork");
chicago.add("new jersy");
chicago.add("dallas");
map.put("chicago", chicago);
等等。
然后你要检查的条件是
if (map.containsKey(a) && map.get(a).contains(b)) {
...
}