简体   繁体   中英

Pass an ArrayList<Object> as an argument to a method, process the arrayList and return it - Java

EDIT:

Sorry forr the misspellings and typos, I didn't want to put my code here so I tried to make a new look a like code to express my question.

Here is the actual code I'm using, I just removed some parts of it as they are not related to my question, I think, otherwise just ask me and I'll put it here as well.

Heres the actual code:

public class Dados {

    private String sta;
    private String ap;
    private int startTime;
    private int endTime;
    private int repetitionSTA;
    private int pingPong;
    private int tt_previous;
    private int tt_next;
    private int id;

    public Dados(int id, int startTime, int endTime, String ap, String sta, int repetitionSTA, int ttprevious, int ttnext, int ppong)
    {
        this.sta = sta;
        this.ap = ap;
        this.startTime = startTime;
        this.endTime=endTime;
        this.pingPong = ppong;
        this.tt_next = ttnext;
        this.tt_previous = ttprevious;
        this.id = id;
        this.repetitionSTA = repetitionSTA;
    }

    // SET

    public void setPingPong()
    {
        this.pingPong = 1;
    }


    //GET

    public int getPingPong()
    {
        return this.pingPong;
    }

}

//another class from now on

public class Queries extends LigarBD{

    String dbtime = null; 

    int id = 1;

    TreeMap<Integer, ArrayList> tmValores = new TreeMap<>();
    ArrayList<Dados> listaObjectos = new ArrayList<>();
    ArrayList<Dados> listaObjectos2 = new ArrayList<>();


    public ArrayList getUniqueStations(String server)
    {
        ArrayList<String> listaSTA = new ArrayList<>();

        String query = "SELECT distinct calling_station_id FROM java_logs;";

        try
        {
            super.ligar(server);
            Statement s = super.getConexao().createStatement();
            ResultSet rs = s.executeQuery(query);
            while (rs.next())
            {
                listaSTA.add(rs.getString(1));
            }
            rs.close();
            s.close();
            super.desligar(super.getConexao());

        }
        catch (Exception e)
        {
            JOptionPane.showMessageDialog(null, "Error at listing all unique stations. Reason -> "+e.getMessage());
            System.out.println("Error at listing all unique stations. Reason ->  "+e.toString());
        }

        return listaSTA;
    }


    public ArrayList getStationData(String mac, String server)
    {

        try 
        {
            super.ligar(server);
            Statement s = getConexao().createStatement();

            ResultSet rs = s.executeQuery("SELECT timestamp-acct_session_time, timestamp, called_station_id, calling_station_id "
                                        + "FROM java_logs where calling_station_id = '"+mac+"';"); // retirar STA da query *******************
            //System.out.println("Executing the Query on+"+server+" - UniqueSTA - Query number: 1?");
            int repetitionSTA=1;
            while (rs.next()) 
            {              
                Dados d = new Dados(id, rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getString(4), repetitionSTA, 0, 0, 0);

                listaObjectos2.add(d);
                repetitionSTA++;
                id++;
            }

            rs.close();
            s.close();
            super.desligar(super.getConexao());
        }
        catch (Exception e) 
        {
            JOptionPane.showMessageDialog(null,"Error at Select Query. Reason -> "+e.getMessage());
        }

        return listaObjectos2;
    }

}

Another class:

public class Pingpong {

    ArrayList<Dados> dadosArray = new ArrayList<>();



    Queries q = new Queries();

    TreeMap<Integer, ArrayList> mapa = new TreeMap<>();
    ArrayList<Dados> arrayDeDados = new ArrayList<>();


    public ArrayList detectPingPongArray(int threshold_access_session_time, int threshold_transition_time, ArrayList<Dados> dadosSTA)
    {
        dadosArray=dadosSTA;
        for(int i = 1; i<arrayDeDados.size()-1; i++)
        {
            dadosArray.get(i).setPingPong();
        }
        return dadosArray;
    }


}

And here is where I'm printing each object one by one:

ArrayList<Dados> dadosSTA = new ArrayList<>();
        ArrayList<Dados> dataForPPong = new ArrayList();

        ArrayList uniqueSTA = q.getUniqueStations("localserver");

        for(int i = 0; i<uniqueSTA.size(); i++)
        {
            dadosSTA = q.getStationData(uniqueSTA.get(i).toString(), "localserver");
            dataForPPong = p.detectPingPongArray(5, 3, dadosSTA);

        }

        for(int i=0; i<dataForPPong.size(); i++)
        {
            System.out.println("ID: "+dataForPPong.get(i).getId()+" STA: "+dataForPPong.get(i).getStation()
                    + " PingPong: "+dataForPPong.get(i).getPingPong());
        }

So I was expecting it to change the value of pingPong in all objects to 1 but it doesn't.

I think the problem is with the returning from the method detectPingPongArray but I don't know where is the mistake.

Anyone can pinpoint the problem here?

The Problem

I'd say there are some bad practices in your code, such as disregarding the generics in ArrayList s, but let's get to the point.

It seems to me, that your problem is in the following method:

public ArrayList detectPingPongArray(
        int threshold_access_session_time,
        int threshold_transition_time,
        ArrayList<Dados> dadosSTA
) {
    dadosArray=dadosSTA;
    for(int i = 1; i<arrayDeDados.size()-1; i++) {
        dadosArray.get(i).setPingPong();
    }
    return dadosArray;
}

This is your code, just with a different formatting to fit in the answer.

The method receives an ArrayList<Dados> dadosSTA , which you assign to dadosArray .
You return this same variable, and you want to perform modifications on it.

However, you are iterating over arrayDeDados 's size, which is a different ArrayList<Dados> , and, from what you give us, is also an empty list.

ArrayList<Dados> arrayDeDados = new ArrayList<>();

Thus, since the size() of an empty list is zero, no iterations are performed, and setPingPong() is never called.


Tips

As requested, I'm also adding some tips for the future.

  1. Although not necessarily a bad practice, more of a personal preference, I wouldn't name my classes / variables in portuguese (which it seems to be in this case), or any language other than english. It keeps the code more readable for others, in situations such as this.

  2. public class Queries extends LigarBD
    I'm not sure that a class to perform queries on a database should extend a class that connects to a database. Instead, it would seem more appropriate to use a class that connects to the database.

    This is easily seen by some patterns in your code, such as super.ligar() , super.getConexao() , super.desligar() , which you do in both methods you shared with us. You seem to be interested in using the interface provided by LigarBD , and not extend it, or add functionality to it. You could change this by declaring an instance variable of type LigarBD , and using it accordingly.

  3. public ArrayList detectPingPongArray
    Here, you throw away the generic information associated with the ArrayList . If you know you'll be returning an ArrayList<Dados> , and you want the callers of this method to know that too, you should declare the method as follows:
    public ArrayList<Dados> detectPingPongArray

    This way, the callers will expect an ArrayList<Dados> , instead of an ArrayList of something (potentially introducing unsafe casts / operations).


Further Analysis

I'm also not sure if this is on purpose, but I've found something rather curious in your code.

ArrayList<Dados> dadosSTA = new ArrayList<>();
ArrayList<Dados> dataForPPong = new ArrayList();

ArrayList uniqueSTA = q.getUniqueStations("localserver");

for(int i = 0; i<uniqueSTA.size(); i++)
{
    dadosSTA = q.getStationData(uniqueSTA.get(i).toString(), "localserver");
    dataForPPong = p.detectPingPongArray(5, 3, dadosSTA);
}

for(int i=0; i<dataForPPong.size(); i++)
{
    System.out.println("ID: "+dataForPPong.get(i).getId()+" STA: "+dataForPPong.get(i).getStation()
            + " PingPong: "+dataForPPong.get(i).getPingPong());
}

The first for loop just assigns new values to the variables, doing nothing with them and constantly overwriting them.

Probably, you want this loop to also include the second loop, so that you effectively print all values, for every ArrayList that is assigned to dataForPPong . Or you'll just add something else inside this loop in the future, but I wanted to point out that this may be a future source of bugs.

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