java arraylist包含对象上的类型
我有一个对象边,它有5种不同的整数类型与对象关联。像这样:java arraylist包含对象上的类型,java,arrays,list,arraylist,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; } pub
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中是否存在任意整数。。。。有办法做到这一点吗
感谢您在advanced中将此方法添加到
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
将此方法添加到边缘
类中
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
}
另外,不要使用原始类型compariable
,您可能希望compariable
使用以下内容:
public List<Integer> asList() {
Arrays.asList(weight, tox, toy, fromx, fromy);
}
公共列表asList(){
数组。asList(重量、毒性、玩具、fromx、fromy);
}
使用以下方法:
public List<Integer> asList() {
Arrays.asList(weight, tox, toy, fromx, fromy);
}
公共列表asList(){
数组。asList(重量、毒性、玩具、fromx、fromy);
}
等等,你想要一个列表
还是列表
?等等,你想要一个列表
还是列表
?啊,谢谢,所以当使用Comparable时,我只说public int compareTo(Edge obj)而不是public int compareTo(Object obj),对吗?很高兴我能帮上忙。别忘了在这个答案上打绿色复选标记!啊,谢谢,所以当使用Comparable时,我只说public int compareTo(边缘对象),而不是public int compareTo(对象对象对象),对吗?很高兴我能帮上忙。别忘了在这个答案上打绿色复选标记!