我想你有某种对类,让我们这样说:
class MyPair {
public int head, tail;
public MyPair(int head, int tail) {
this.head = head;
this.tail = tail;
}
...
}
非常标准的方法是使用 for 循环并根据您要查找的内容比较每对的变量。例如,假设您创建了一个填充了一些元素的 ArrayList:
List<MyPair> myList = new ArrayList<>();
myList.add(new MyPair(1, 2));
myList.add(new MyPair(3, 4));
...
然后,您可以像这样使用 for 循环:
boolean containsHead(List<MyPair> list, int value) {
for(MyPair pair : list) {
if(pair.head == value) {
return true;
}
}
return false;
}
用法:
containsHead(myList, 3);
>> true
你可以对尾巴做非常相似的方法。
另一种方法是更改您的结构,例如,您可以使用“列表对”而不是使用对列表 - 创建 2 个列表,如下所示:
List<Integer>
heads = new ArrayList<>(),
tails = new ArrayList<>();
heads.add(1);
tails.add(2);
...
用法:
tails.contains(2);
>> true
我想到的最后一种方法,但我不建议使用,是覆盖 equals 方法,使您的类表现为您设置的任何一项。
class MyPair {
public int head, tail;
public MyPair(int head, int tail) {
this.head = head;
this.tail = tail;
}
private static boolean asHead = true;
public static MyPair searchOf(int x) {
return new MyPair(x, x);
}
public static void behaveAsHead() {
asHead = true;
}
public static void behaveAsTail() {
asHead = false;
}
@Override
public boolean equals(Object other) {
if (other instanceof MyPair) {
MyPair otherPair = (MyPair) other;
return asHead ? (head == otherPair.head) : (tail == otherPair.tail);
}
return false;
}
}
用法:
// search for tail of value 4
MyPair.behaveAsTail();
myList.contains(MyPair.searchOf(4));
>> true