简体   繁体   English

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

[英]How to access values stored in ArrayList in Java?

I'm a total newbie to Java, and until now all I've done was draw some shapes and flags. 我是Java的新手,到目前为止,我所做的只是绘制一些形状和标志。 I'm struggling to understand the code I've been given. 我正在努力理解给出的代码。 I need to access values stored in an ArrayList within another class. 我需要访问存储在另一个类中的ArrayList中的值。 I'm not sure I'm making any sense, so here are the two classes Seat and Mandate: 我不确定我是否有意义,因此这是Seat和Mandate这两个类:

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;
    }
}

The main class contains code that feeds data from 2 text files into Seat and Mandate. 主类包含将2个文本文件中的数据馈送到Seat和Mandate中的代码。 From there I managed to access the date in Seat. 从那里,我设法在Seat中访问了日期。 Like here: 像这儿:

//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";
}

Now,instead of getting just the mp for Edinburgh South I need to get the vote values, compare them to each other, take the second biggest and display the associate party value. 现在,我不仅需要获得爱丁堡南部的议员席位,还需要获取投票值,将它们进行相互比较,选出第二大的选票并显示准党的价值。 Would appreciate any help, like how to access data from that Array would help me get started at least. 我们将不胜感激,例如如何从该阵列访问数据至少可以帮助我入门。

An element in an ArrayList is accesses by its index. ArrayList的元素通过其索引进行访问。 Seems you can just sort your ArrayList based on the vote values of the objects which are in the list. 似乎您可以根据列表中对象的vote值对ArrayList排序。 For this you may want to look here: Sort ArrayList of custom Objects by property 为此,您可能需要看这里: 按属性对自定义对象的ArrayList进行排序

Of course sorting is maybe too much for your given problem. 当然,对于您给定的问题,排序可能太多了。 Alternatively, 或者,
you may just iterate through the list and pick the two objects with the highest 您可以只遍历列表,然后选择两个具有最高的对象
votes values as you go. 随便votes

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

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