我想要一个排序的映射如下:
srcAddr, dstAddr, srcPort, dstPort, protocol as keys
和列表的值作为
每个键的 packetLength、timeArrival。
是否可以在单独的类中实现它们?我很困惑它是否会以这种方式工作。
更新:
我收到一条错误消息,表明我没有覆盖抽象方法 compareTo()。你能帮我吗?
package myclassifier;
import java.io.Serializable;
import java.util.*;
public class Flows implements Serializable, Comparable {
String srcAddr, dstAddr, srcPort, dstPort, protocol;
public int compareTo(Flows other) {
int res = this.srcAddr.compareTo(other.srcAddr);
if (res != 0) {
return res;
}
res = this.dstAddr.compareTo(other.dstAddr);
if (res != 0) {
return res;
}
res = this.srcPort.compareTo(other.srcPort);
if (res != 0) {
return res;
}
res = this.dstPort.compareTo(other.dstPort);
if (res != 0) {
return res;
}
return this.protocol.compareTo(other.protocol);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dstAddr == null) ? 0 : dstAddr.hashCode());
result = prime * result + ((dstPort == null) ? 0 : dstPort.hashCode());
result = prime * result + ((srcAddr == null) ? 0 : srcAddr.hashCode());
result = prime * result + ((srcPort == null) ? 0 : srcPort.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Flows other = (Flows) obj;
if (dstAddr == null) {
if (other.dstAddr != null)
return false;
} else if (!dstAddr.equals(other.dstAddr))
return false;
if (dstPort == null) {
if (other.dstPort != null)
return false;
} else if (!dstPort.equals(other.dstPort))
return false;
if (srcAddr == null) {
if (other.srcAddr != null)
return false;
} else if (!srcAddr.equals(other.srcAddr))
return false;
if (srcPort == null) {
if (other.srcPort != null)
return false;
} else if (!srcPort.equals(other.srcPort))
return false;
return true;
}
}
最佳答案
你可以写一个,比如一个“MyKey”类,其中包含 srcAddr、dstAddr、srcPort、dstPort 和协议(protocol)作为它的成员变量。您必须小心覆盖此类的 equals
和 hashCode
方法。此类还必须实现 Comparable指示如何根据成员(member)字段确定您的排序的界面。
您可以实现一个类 MyValue 以将 packetLength、timeArrival 等作为成员。这将是您要存储在 map 中的值。
使用TreeMap根据 MyKey 存储 MyValue。
关于使用值列表实现的 Java SortedMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3448093/