Reputation:
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.
Upvotes: 0
Views: 6382
Reputation: 241
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]
Upvotes: 0
Reputation: 6351
2 options:
Pair<UUID, Event> pair = Pair.of(id, event)
Upvotes: 1
Reputation: 95
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() + ")"; }
}
Upvotes: 0