我完全不喜欢编程(昨天开始……)和Java,所以请原谅任何愚蠢的错误和非常糟糕的代码(我不知道如何订购/格式化).我已经完成了制作视频库存的任务,我希望能够搜索库存以检查特定视频是否在那里.
我知道我可以使用contains来执行此操作,但我不能使用它来处理我的自定义对象ArrayList(视频),我希望它能够搜索所有数据(下面的每个InventoryRow).我已经覆盖了equals和HashCode,但它仍然无法工作 – 每当我尝试运行代码时,它总会告诉我即使视频在那里也无法找到视频. (仅供参考我在租用和检查功能下使用包含在我的代码末尾)
我真的很感激任何帮助,因为我一整天都在谷歌搜索无济于事.如果这不能做或其他方法会更好,请告诉我!谢谢.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
class InventoryRow {
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((availability == null) ? 0 : availability.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result
+ ((returndate == null) ? 0 : returndate.hashCode());
result = prime * result + ((type == null) ? 0 : type.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;
InventoryRow other = (InventoryRow) obj;
if (availability == null) {
if (other.availability != null)
return false;
} else if (!availability.equals(other.availability))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (returndate == null) {
if (other.returndate != null)
return false;
} else if (!returndate.equals(other.returndate))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
private String name;
private String type;
private Character availability;
private String returndate;
public InventoryRow(String name,String type,Character availability,String returndate) {
this.name = name;
this.type = type;
this.availability = availability;
this.returndate = returndate;
}
public String getReturndate() {
return returndate;
}
public void setReturndate(String returndate) {
this.returndate = returndate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Character getAvailability() {
return availability;
}
public void setAvailability(Character availability) {
this.availability = availability;
}
public String toString() {
return name + " " + type + " " + availability + " " + returndate;
}
}
public class InventorySort {
public static void main(String[] args) {
List
最佳答案
你可以使用包含.但是,对于编程的第一天,简单地迭代您的库存,将输入字符串与视频名称进行比较可能更容易理解:
boolean foundIt = false;
for (InventoryRow ir : videos) {
if (line3.equals(ir.getName())) {
foundIt = true;
break;
}
}
if (foundIt) {
System.out.println("Video found!");