如何在Java中访问存储在ArrayList中的值?

时间:2014-11-27 23:45:59

标签: java arrays eclipse class arraylist

我是Java的新手,直到现在我所做的一切都是画出一些形状和旗帜。我很难理解我给出的代码。我需要访问存储在另一个类中的ArrayList中的值。我不确定我是否有任何意义,所以这里有两类座位和任务:

package wtf2;

import java.util.*;        

public class Seat {
    public int index;
    public String place;
    public int electorate;
    public String mp;
    public String party;
    public String prev;
    public ArrayList<Mandate> results;

    public Seat(int index, String place) {
        this.place = place.trim();
        this.index = index;
        this.results = new ArrayList<Mandate>();
    }

    public void addMandate(Mandate m) {
        //First candidate is always the MP
        if (mp == null) {
            mp = m.candidate;
            party = m.party;
        }
        results.add(m);
    }

    public String toString() {
        return "[" + this.index + "," + this.place + "]";
    }
}

class Mandate {
    public String candidate;
    public String party;
    public int vote;

    public Mandate(String candidate, String party, int vote) {
        this.candidate = candidate;
        this.party = party;
        this.vote = vote;
    }
}

主类包含将来自2个文本文件的数据提供给席位和授权的代码。从那里我设法访问Seat的日期。像这里:

//Who is the MP for "Edinburgh South"
public static String qA(List<Seat> uk) {
    for (Seat s : uk)
        if (s.place.startsWith("Edinburgh South"))
            return (s.mp);
    return "Not found";
}

现在,我不需要获得爱丁堡南部的mp,而是需要获得投票值,将它们相互比较,取第二大值并显示关联方价值。 非常感谢任何帮助,比如如何从该阵列访问数据将帮助我至少开始。

1 个答案:

答案 0 :(得分:1)

ArrayList中的元素是其索引的访问。 似乎您可以根据列表中对象的ArrayList值对vote进行排序。 为此,您可以查看此处:Sort ArrayList of custom Objects by property

当然,对于您遇到的问题,排序可能太多了。另外,
你可以只遍历列表并选择具有最高
的两个对象 当你去votes时。{/ p>