我必须创建一个equals方法,如果Politicians'标题是一样的。我如何比较字符串?
到目前为止,这是我尝试编写的方式:
import socket
import struct
import binascii
rawSocket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003))
while True:
packet = rawSocket.recvfrom(2048)
ethernet_header = packet[0][0:14]
ethernet_detailed = struct.unpack(“!6s6s2s”, ethernet_header)
arp_header = packet[0][14:42]
arp_detailed = struct.unpack(“2s2s1s1s2s6s4s6s4s”, arp_header)
# skip non-ARP packets
ethertype = ethernet_detailed[2]
if ethertype != ‘\x08\x06’:
continue
source_mac = binascii.hexlify(arp_detailed[5])
dest_ip = socket.inet_ntoa(arp_detailed[8])
if source_mac == ‘74c24671971c’:
print “Tide button pressed!, IP = “ + dest_ip
然而,它总是返回false。即使我测试:
public class Politician implements Priority{
private String name, title;
private int a;
public Politician(String n, String t, int p){
name=n;
title=t;
a=p;
}
public boolean equals(Politician a){
if(title.equals(a.title))
return true;
return false;
}
之前我写过equals()并且我不知道为什么它不再工作了
答案 0 :(得分:8)
public boolean equals(Politician a)不会覆盖类java.lang.Object中的equals方法。
声明为公共布尔值等于(对象a)以覆盖该方法。
public boolean equals(Object a) {
Politician p = (Politician) a;
return title.equals(p.title);
}
顺便说一句,在政治家课程中使用p.title是完全合法的,即使在政治家课程中标题是私人的。查看这篇文章:Access private field of another object in same class
答案 1 :(得分:1)
试试这个:
public class Politician extends Priority{
public String name, title;
public int a;
public Politician(String n, String t, int p) {
name = n;
title = t;
a = p;
}
public boolean equals(Object o) {
Politician a = (Politician) o;
//System.out.println(a.title +" - "+title);
if (title.equals(a.title)) {
return true;
}
return false;
}
public static void main(String[] args) {
Priority t4 = new Politician("Arnie", "Governor", 4);
Politician t5 = new Politician("Bill", "Governor", 10);
System.out.println(t5.equals(t4));
System.out.println(t4.equals(t5));
}
}