java arraylist包含对象的类型

时间:2013-04-24 21:11:38

标签: java arrays list arraylist

我有一个对象边缘,它有5个与对象关联的不同整数类型。像这样:

public class Edge implements Comparable {

int weight, tox, toy, fromx, fromy;

public Edge(int x1, int y1, int x2, int y2, int wei) {
    tox = x1;
    toy = y1;
    fromx = x2;
    fromy = y2;
    weight = wei;

}

public int compareTo(Object obj) {

我想创建这些obj的arraylist然后在列表中调用contains来查看任何这些数据类型的列表中是否有任意整数,edge.tox edge.toy edge.fromx或edge.fromy ....有没有办法做到这一点?

先谢谢你

2 个答案:

答案 0 :(得分:2)

将此方法添加到Edge

public boolean contains(int num) {
    if(tox == num) return true;
    if(fromx == num) return true;
    if(toy == num) return true;
    if(fromy == num) return true;
    return false;
}

然后你可以这样做:

public Edge getEdgeFromNumber(int number) {
  for(Edge e : myArrayList) { 
      if(e.contains(number)) return e;
  }
  return null; // there are no such edges
}

另外,不要使用原始类型Comparable,您可能需要Comparable<Edge>

答案 1 :(得分:2)

使用此:

public List<Integer> asList() {
    Arrays.asList(weight, tox, toy, fromx, fromy);
}