java - хабр - регулярные выражения. 3-е изд.
Java: как хранить данные три раза в списке? (4)
Каков наилучший способ в java хранить данные в тройке в списке?
[a, b, c]
[a, b, c]
...
Я обычно использую HashMap для пары ключей данных + значение. Должен ли я перейти на HashMap + Arraylist? или ArrayList + ArrayList?
благодаря
Если вы ожидаете отслеживать четыре или более объектов вместе, найдите что-то, что масштабируется.
Если бы вы решили, что хотите понятие «тройка», чтобы получить некоторые идеи, вы можете следовать шаблону Sun для javac.util.Pair :
public class Pair<A, B> {
public final A fst;
public final B snd;
public Pair(A fst, B snd) {
this.fst = fst;
this.snd = snd;
}
public String toString() {
return "Pair[" + fst + "," + snd + "]";
}
private static boolean equals(Object x, Object y) {
return (x == null && y == null) || (x != null && x.equals(y));
}
public boolean equals(Object other) {
return
other instanceof Pair<?,?> &&
equals(fst, ((Pair<?,?>)other).fst) &&
equals(snd, ((Pair<?,?>)other).snd);
}
public int hashCode() {
if (fst == null) return (snd == null) ? 0 : snd.hashCode() + 1;
else if (snd == null) return fst.hashCode() + 2;
else return fst.hashCode() * 17 + snd.hashCode();
}
public static <A,B> Pair<A,B> of(A a, B b) {
return new Pair<A,B>(a,b);
}
}
или следовать за android.util.Pair
public class Pair<F, S> {
public final F first;
public final S second;
public Pair(F first, S second) {
this.first = first;
this.second = second;
}
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Pair)) return false;
final Pair<F, S> other;
try {
other = (Pair<F, S>) o;
} catch (ClassCastException e) {
return false;
}
return first.equals(other.first) && second.equals(other.second);
}
public int hashCode() {
int result = 17;
result = 31 * result + first.hashCode();
result = 31 * result + second.hashCode();
return result;
}
//...
}
Кажется, я согласен с whirlwin.
Общий консенсус, хотя я не могу найти доказательства сейчас, предусматривает, что параметризованные типы должны быть не более 2. Вот почему каждый класс, который я могу представить в библиотеке коллекций Java, имеет максимум два параметризованных типа.
Код становится загроможденным, когда у вас есть три параметризованных типа. Просто слишком много>, <для решения.
Я предлагаю, что сказал whirlwin и создал объект, который содержит три конкретных типа, которые вам нужны.
public class Triple<F, S, T> {
public final F first;
public final S second;
public final T third;
public Triple(F first, S second, T third) {
this.first = first;
this.second = second;
this.third = third;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Triple)) {
return false;
}
Triple<?, ?, ?> p = (Triple<?, ?, ?>) o;
return first.equals(p.first) && second.equals(p.second) && third.equals(p.third);
}
private static boolean equals(Object x, Object y) {
return (x == null && y == null) || (x != null && x.equals(y));
}
@Override
public int hashCode() {
return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()) ^ (third == null ? 0 : third.hashCode());
}
public static <F, S, T> Triple <F, S, T> create(F f, S s, T t) {
return new Triple<F, S, T>(f, s, t);
}
}
public class Triplet<T, U, V> {
private final T first;
private final U second;
private final V third;
public Triplet(T first, U second, V third) {
this.first = first;
this.second = second;
this.third = third;
}
public T getFirst() { return first; }
public U getSecond() { return second; }
public V getThird() { return third; }
}
И для создания списка:
List<Triplet<String, Integer, Integer>> = new ArrayList<>();