简体   繁体   中英

How to call and contain ArrayList<Object>

I have a txt-file like this and I'm going through it

wlan_AP : lcb-kasse |  ActiveUsers : 1
wlan_AP : WLAN-C7B702 |  ActiveUsers : 1
wlan_AP : Telekom |  ActiveUsers : 1
wlan_AP : Telekom |  ActiveUsers : 1
wlan_AP : FRITZ!Box |  ActiveUsers : 1
wlan_AP : Telekom |  ActiveUsers : 1
wlan_AP : Sperling2 |  ActiveUsers : 1
wlan_AP : lcb-kasse |  ActiveUsers : 2
wlan_AP : WLAN-C7B702 |  ActiveUsers : 2
wlan_AP : Telekom |  ActiveUsers : 2
wlan_AP : Telekom |  ActiveUsers : 2
wlan_AP : FRITZ!Box |  ActiveUsers : 2
wlan_AP : Telekom |  ActiveUsers : 2
wlan_AP : Sperling2 |  ActiveUsers : 2

So I have meausrements of WiFi-AccessPoint Names (wlan_AP) and the number of active Users at the moment.

As you may've seen there are multiple measurements per AccessPoint (eg lcb-kasse )

I want to get the average number of active users at the end of my program.

Therefore I created a new Class called Averager. For every

averagerList = new ArrayList<Averager>();

This class has this variables

private String wlanAp;  
ArrayList<Integer> measurements = new ArrayList<Integer>();

So in the main method I'm going through the txt-file, taking the wlanAp as a String and I'm looking if there is an object with the wlanAp

ArrayList<Averager> averagerList = new ArrayList<Averager>;

if (averagerList.contains(WlanAp))
{
    //it's already existing, just add a new measurement
   mittler.addMeasurement(m.getDb());                       
}
else
{
    averager = new Averager(mWlanAp);
    averagerList.add(averager);
    averager.addMeasurement(m.getActiveUsers());  
}

But my problem - It is creating 14 objects instead of 7. Why? And I don't know how to check if there is already an element with this String name

Thanks for your help, I hope I covered all .. if not just ask

if (averagerList.contains(WlanAp))

This check will not work because WlanAp is a String while averagerList contains Averagers. The two are not equivalent, as per the implementation of their equals methods.

You should be using a Map instead of a List, a map is designed to act as a look up from one value to another while a list is a collection of a single type. Using a map, your code would look like this:

Averager av = map.get(WlanAp);
if ( av == null ) {
    av = new Averager();
    map.put( WlanAp, av );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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