简体   繁体   中英

Store “tuples” of values in ArrayList in Java

I'm trying to store pairs of names and addresses in a collection. Is there a way these values can be grouped together in a tuple? If so, which collection should I use to fulfill this? Whatever collection I use, it should be able to add a tuple with these values, remove the tuple, and list the tuples in the collection.

Thanks.

2 options:

  1. Make a value class that holds the 2 things you need.
  2. Or, for simple cases, just use a Pair class which comes with plenty of libraries, including the famous Apache Commons library. ie Pair<UUID, Event> pair = Pair.of(id, event)

A possible solution may be to create a class Pair. Then you can create instance of Pairs and add them to your ArrayList.

import java.util.ArrayList;

public class Test {
  public static void main(String[] args) {
    Pair pair1 = new Pair(1, 2);
    Pair pair2 = new Pair(2, 3);
    ArrayList<Pair> arrayOfPair = new ArrayList();
    arrayOfPair.add(pair1);
    arrayOfPair.add(pair2);
    for (Pair p : arrayOfPair) {
      System.out.println(p);
    }
  }
}

class Pair<T> {
  T fst;
  T snd;

  public Pair(T fst, T snd) {
    this.fst = fst;
    this.snd = snd;
  }

  T getFst() { return fst; }

  T getSnd() { return snd; }

  public String toString() { return "(" + getFst() + "," + getSnd() + ")"; }
}

You can create a class

class Data {
    private String name;
    private String address;

    public Data(String name, String address) {
        this.name = name;
        this.address = address;
    }
    @Override
    public String toString() {
        return "Name: "+name+" and Address: "+address; 
    }
}

And in the main to add the name and address to the arraylist and print it.

public static void main(String[] args) throws IOException {
    List<Data> information = new ArrayList<>();
    information.add(new Data("John Doe", "Mars"));
    System.out.println(information);

}

An output example: [Name: John Doe and Address: Mars]

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