下面的TestList类里实现了以NodeId来找到Node对象的最大/最小值:
import java.util.*;
public class TestList {
public static void main(String[] args) {
List<Node> input = new ArrayList<Node>();
Node Node1=new Node(1,"acc");
Node Node2=new Node(2,"agg");
Node Node3=new Node(3,"core");
input.add(Node1);
input.add(Node2);
input.add(Node3);
System.out.println(input);
//max和min方法在Collections类中,若要将Node类对象作为参数,则Node类需要实现Comparable接口
System.out.println("最大值: " + Collections.max(input));
System.out.println("最小值: " + Collections.min(input));
}
}
//Node类实现Comparable接口:
class Node implements Comparable <Node>{
Integer NodeId;
String NodeType;
public Node(Integer id, String type)
{
NodeId=id;
NodeType=type;
}
public Integer getNodeId() {
return NodeId;
}
public void setNodeId(Integer nodeId) {
NodeId = nodeId;
}
@Override //覆盖Comparable接口里的compareTo方法
public int compareTo(Node o) {
return NodeId.compareTo(o.getNodeId());//以NodeId进行比较
}
}