简体   繁体   中英

java arraylist contains type on object

I have an object Edges which has 5 different integer types associated with the object. like this:

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) {

I want to make an arraylist of these objs and then call contains on the list to see if an arbitrary integer is in either the list at any of these data types, edge.tox edge.toy edge.fromx or edge.fromy .... is there a way to do this?

thank you in advanced

Add this method to the Edge class

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;
}

Then you can just do:

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

Also, don't use the raw type Comparable , you probably want Comparable<Edge>

Use this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM