简体   繁体   中英

Reference ArrayList object to objects of other ArrayLists

I have 3 different classes; Contestant, Event and Result.

public class Contestant {

public static ArrayList<Contestant> allContestants = new ArrayList<>();

private int contestantId;
private String firstName;
private String lastName;

public Contestant (int contestantId, String firstName, String lastName) {
    this.contestantId = contestantId;
    this.firstName = firstName;
    this.lastName = lastName;
}

public class Event {

public static ArrayList<Event> allEvents = new ArrayList<>();

private String eventName;

public Event (String eventName) {
    this.eventName = eventName;
}

public class Result {

public static ArrayList<Result> allResults = new ArrayList<>();

private double result;
private int attemptNumber;

public Result (double result, int attemptNumber) {
    this.result = result;
    this.attemptNumber = attemptNumber:
}

The classes have different methods for adding new Contestant objects, new Event objects and new Result objects to each ArrayList. Each contestant can participate in multiple events and for each event they can create multiple results.

What I want to achieve is for each Result object to reference a Contestant ArrayList object as well as an Event ArrayList object - how can I best link them?

Your event class should be like this ,instead of array list you can use Hashmap.

public class Event {
//In this you can have contestantId as key and Event as value
public static Map<String, Event> allEvents = new HashMap<String, Event>();

private String eventName;

public Event (String eventName) {
    this.eventName = eventName;
}

And your result class should be like this:

public class Result {
//In this you can have eventName as key and Result as value
public static Map<String, Result> allResults = new HashMap<String, Result>();

private double result;
private int attemptNumber;

public Result (double result, int attemptNumber) {
    this.result = result;
    this.attemptNumber = attemptNumber:
}

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