2013-04-24 80 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); 
}