针对对象类型
问题描述:
public void searchWatch(long srch){
long s = srch;
boolean found = false;
for(int i = 0; i<watchStore.size();i++){
Watch fd = watchStore.get(i);
if(fd.equals(s)){
System.out.print("item found");
found = true;
}
if(!found){
System.out.println("no such record");
}
}
}
此的ArrayList搜索一个特定的输入是从我类中的一个的代码片段。我在这里的问题是我想测试类型为Watch的数组列表的长类型的特定输入。序列号是否存在于数组列表中。针对对象类型
但它失败,因为一个错误“不兼容的类型.equal()”什么与上面的代码
下面的问题是修改后的代码
public Watch findWatchBySerialNumber(long srch){
long s = srch;
Watch watch = null;
for(int i = 0; i<watchStore.size();i++){
watch = watchStore.get(i);
if(watchStore.contains(s)){ // this pop an error called suspicious call to java.utit.Collection.contains
System.out.print("item found");
return watch;
}
}
System.out.print("item not found");
return null; // watch is not found.
}
请如何我能解决这个问题吗?
答
替换:
Watch fd = watchStore.get(i);
有了:
Watch fd = watchStore.get(i);`
// use getter method
String fdString = fd.getSerial();
if(fdString.equals(s)){
System.out.print("item found");
found = true;
}
看看是否有帮助。
答
'fd'是的对象手表和's'是的对象字符串。由于这些是两个不同的类,运行fd.equals(s)会抛出错误。 得到它的工作,尝试重写toString()方法在观察类,然后做
fd.toString().equals(s)
答
如果试图通过随后的序列号找到:
public void searchWatch (long srch){
boolean isFound = false;
Watch fd = null; // declaring variable out of the loop is better.
for(int i = 0; i<watchStore.size();i++){
fd = watchStore.get(i);
if(fd.getSerialNumber.equals(srch)){
System.out.print("item found");
isFound = true;
}
if(!found){
System.out.println("no such record");
}
}
}
我的建议:如果你写你的方法名称作为搜索或找到你应该返回一个对象。如果您只需要知道“是否存在”,则可以为您的方法指定一个名称:isWatchExist()
并添加布尔返回类型。
public boolean isWatchExist (long serialNumber) {
Watch watch = null; // declaring variable out of the loop is better.
for(int i = 0; i < watchStore.size(); i++){
watch = watchStore.get(i);
if(watch.getSerialNumber.equals(serialNumber)){
System.out.print("item found");
return true;
}
}
System.out.println("no such record");
return false;
}
如果您需要查找对象,则应该添加对象的返回类型。给出一个清楚描述你的方法目标的名字。
public Watch findWatchBySerialNumber (long serialNumber){
boolean isFound = false;
Watch watch = null; // declaring variable out of the loop is better. and name of you variable should describe your object, same name is better.
for(int i = 0; i < watchList.size(); i++){ // your list name should be "watchList".
watch = watchList.get(i);
if(fd.getSerialNumber.equals(serialNumber)){
System.out.print("item found");
return watch;
}
}
System.out.print("item not found");
return null; // watch is not found.
}
fd是'Watch'类型,而s是'String'类型。 –
您应该发布您的Watch对象详细信息以及您要搜索的字段。如果您需要搜索“watch”的“watch id”,则应该写入“watch.getId.equals(srch);”我认为“手表ID”也是很长的。 –
嗯,但我对代码进行了更正,而不是通过名称进行搜索,我实际上想通过序列号进行搜索......所以我将代码更改为接受long类型的参数。 – Nabstar