2013-04-24 82 views
0

我有一个对象具有与该对象关联的5种不同整数类型的对象。像这样:java arraylist在对象上包含类型

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,然后调用包含在名单上看到,如果任意整数处于或者列表中的任何一种数据类型,edge.tox edge.toy edge.fromx或edge.fromy ....有没有办法做到这一点?

感谢你在先进

+0

等等,你想要一个'列表'或列表'? – durron597 2013-04-24 21:16:24

回答

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

ahh谢谢,所以当使用Comparable 我只是说public int compareTo(Edge obj)而不是public int compareTo(Object obj),对吗? – user1807880 2013-04-24 21:19:51

+0

nvm都很棒:) – user1807880 2013-04-24 21:23:39

+0

很高兴我能帮到你。不要忘记绿色选中此答案! – durron597 2013-04-24 21:30:07

2

使用t他:

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