简体   繁体   English

传递一个ArrayList <Object> 作为方法的参数,处理arrayList并将其返回-Java

[英]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. 因此,我期望它可以将所有对象中pingPong的值更改为1,但事实并非如此。

I think the problem is with the returning from the method detectPingPongArray but I don't know where is the mistake. 我认为问题出在方法detectPingPongArray的返回上,但我不知道错误在哪里。

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. 我想说您的代码中有一些不良做法,例如不理会ArrayList的泛型,但让我们开始讨论。

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 . 该方法接收一个ArrayList<Dados> dadosSTA ,您将其分配给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. 但是,您正在遍历arrayDeDados的大小,这是一个与 ArrayList<Dados> 不同的大小,并且根据您提供的信息,它也是一个列表。

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

Thus, since the size() of an empty list is zero, no iterations are performed, and setPingPong() is never called. 因此,由于空列表的size()为零,因此不会执行任何迭代,并且永远不会调用setPingPong()


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. 您的代码中的某些模式super.ligar()例如super.ligar()super.getConexao()super.desligar()很容易看出来,您可以在与我们共享的两种方法中进行操作。 You seem to be interested in using the interface provided by LigarBD , and not extend it, or add functionality to it. 您似乎对使用LigarBD提供的接口LigarBD ,而不是对其进行扩展或添加功能。 You could change this by declaring an instance variable of type LigarBD , and using it accordingly. 您可以通过声明类型为LigarBD的实例变量并相应地使用它来更改此设置。

  3. public ArrayList detectPingPongArray
    Here, you throw away the generic information associated with the ArrayList . 在这里,您丢弃了与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: 如果您知道将返回ArrayList<Dados> ,并且希望此方法的调用者也知道该方法,则应按以下方式声明该方法:
    public ArrayList<Dados> detectPingPongArray

    This way, the callers will expect an ArrayList<Dados> , instead of an ArrayList of something (potentially introducing unsafe casts / operations). 这样,调用者将期望ArrayList<Dados> ,而不是某些东西ArrayList (可能会引入不安全的强制类型转换/操作)。


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. 第一个for循环只是为变量分配新值,对它们不执行任何操作并不断覆盖它们。

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 . 可能您希望此循环还包括第二个循环,以便有效地打印分配给dataForPPong每个ArrayList所有值。 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. 或者您将来会在此循环中添加其他内容,但我想指出的是,这可能是将来的错误来源。

传安 ArrayList<customobject> 到接受 ArrayList 作为参数的 function<object> 在 Java<div id="text_translate"><p> 我正在编写一个通用的 java-android function,它将接受ArrayList<Object>作为其参数之一,这样我就可以在我的整个应用程序中使用,而不管 ArrayList 元素的类型如何。</p><p> 这是我的 function:</p><pre> public GenericDisplayAdapter(Activity activity, ArrayList<Object> arrData) { this.m_ArrData = arrData; inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); }</pre><p> 当我尝试将我的ArrayList<CustomObject>作为参数传递给此 function 时,出现错误“无法从ArrayList<CustomObject>转换为ArrayList<Object> ”,</p><pre> m_LVStructDamageHeader.setAdapter(new GenericDisplayAdapter( (Activity)this, (ArrayList<Object>)arrStructDamageHeaders));</pre><p> 处理这种情况的最佳方法是什么,谢谢</p></div></object></customobject> - Pass An ArrayList<CustomObject> to a function that accepts as parameter an ArrayList<Object> in Java

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 ArrayList 传递给 Java 中的方法? - How to Pass an ArrayList to a Method in Java? Java ArrayList - 返回ArrayList - Java ArrayList - Return ArrayList 在 Java 中对数组列表的对象使用方法 - Using a method on an object of an arraylist in Java Java ArrayList get()方法不返回Point对象? - Java ArrayList get() method doesn't return Point object? Java 方法读取文本文件并返回 ArrayList 类型 object - Java method to read text file and return ArrayList type object Java反射-传入ArrayList作为要调用的方法的参数 - Java Reflection - Passing in a ArrayList as argument for the method to be invoked 传安 ArrayList<customobject> 到接受 ArrayList 作为参数的 function<object> 在 Java<div id="text_translate"><p> 我正在编写一个通用的 java-android function,它将接受ArrayList<Object>作为其参数之一,这样我就可以在我的整个应用程序中使用,而不管 ArrayList 元素的类型如何。</p><p> 这是我的 function:</p><pre> public GenericDisplayAdapter(Activity activity, ArrayList<Object> arrData) { this.m_ArrData = arrData; inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); }</pre><p> 当我尝试将我的ArrayList<CustomObject>作为参数传递给此 function 时,出现错误“无法从ArrayList<CustomObject>转换为ArrayList<Object> ”,</p><pre> m_LVStructDamageHeader.setAdapter(new GenericDisplayAdapter( (Activity)this, (ArrayList<Object>)arrStructDamageHeaders));</pre><p> 处理这种情况的最佳方法是什么,谢谢</p></div></object></customobject> - Pass An ArrayList<CustomObject> to a function that accepts as parameter an ArrayList<Object> in Java Java ArrayList 方法返回 0 而不是 ArrayList 的实际长度 - Java ArrayList size() method return 0 instead of actual length of the ArrayList Java ArrayList,返回抽象类的ArrayList的访问方法 - Java ArrayList, access method to return ArrayList of abstract class 将arraylist作为参数传递给方法 - Passing an arraylist as argument to method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM