简体   繁体   中英

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. I'm struggling to understand the code I've been given. I need to access values stored in an ArrayList within another class. I'm not sure I'm making any sense, so here are the two classes Seat and 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. From there I managed to access the date in 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. Seems you can just sort your ArrayList based on the vote values of the objects which are in the list. For this you may want to look here: Sort ArrayList of custom Objects by property

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.

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