如何从一个物体拉一个ArrayList的具体数据 [英] How to pull specific data from an object in an arraylist

查看:123
本文介绍了如何从一个物体拉一个ArrayList的具体数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,不知道标题的措辞是正确,但说我有每个数据的两个字符串(比方说,一个Statename的和的cityName)存储到一个ArrayList三个对象。是有可能的状态名作为字符串变量(称之为searchStateName),则必须通过在列表中的对象的方法,搜索输入和比较searchStateName到Statename的ArrayList中的每个对象物的内部,并且当发现匹配有它返回的cityName是相同的对象匹配Statename的?

Ok, not sure if the title worded that correctly but say I have three objects with two strings of data each(Lets say a stateName and a cityName) stored into an arraylist. Is it possible to enter in a state name in as a string variable(call it searchStateName), then have a method search through the objects in the list and compare searchStateName to the stateName inside each object in the arraylist, and when a match is found have it return the cityName that is inside the same object as the matching stateName?

我试图做同样的事情目前并想找出自己,但我一直在做这个了几个小时和我完全丧失。任何人都可以点我在正确的方向?

I am trying to do something similar currently and would like to figure it out myself, but I have been working on this for the past hour and am completely lost. Could anyone point me in the right direction?

推荐答案

这是这种方法。假设你有一个叫做类 SC ,你必须在为他们两个实例变量和getter和setter。您需要初始化内部主其中3个对象:

This is the approach. Say you have a class called SC and you have two instance variables in it and getters and setters for them. You need to initialize 3 objects of them inside your main:

SC a = new SC("Illinois ","Chicago ");
SC b = new SC("Michigan ","Detroit");
SC c = new SC("New York"," New York");

然后创建一个的ArrayList 对象的 SC 并添加 SC的那些3个对象到的ArrayList

And then create an ArrayList of object SC and add those 3 objects of SC to that ArrayList.

ArrayList<SC> list = new ArrayList<SC>();
list.add(a);
list.add(b);
list.add(c);

现在调用搜索状态名称,并返回该城市名称的方法,如果找到它:

Now call the method that search for a state name and returns the city name if it finds it:

this.searchStateName("Illinois");

实际的此方法的实现与的for-each 循环:

public String searchStateName(String stateName){
 String result = "No city found.";
      for (SC sc : list )
         if (sc.getStateName().equalsIgnoreCase(stateName)){
          result = sc.getCityName();
          break;
        }
    }
 return result;
}

如果你不舒服的for-each 循环,那么你可以使用常规的下面循环。我注释掉的目的。但它会正常工作,给你正确的城市名称。

If you are not comfortable with for-each loop then you can use the regular for loop below. I commented out on purpose. But it will work correctly and give you the correct city name.

//public String searchStateName(String stateName){
// String result = null;
//      for (int i = 0; i < list.size(); i++){
//         if (list.get(i).getStateName() .equalsIgnoreCase(stateName)){
//          result = list.get(i).getCityName();
//          break;
//        }
//    }
// return result;
//}

和多数民众赞成它。让我知道如果你需要进一步的帮助。

And thats it. Let me know if you need help further.

这篇关于如何从一个物体拉一个ArrayList的具体数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆