我是Java新手。我正在尝试验证数组列表中的对象列表。
例如,
Class Cars()
{
private String name;
private int year;
}
Cars car = new Cars();
ArrayList<Cars> al = new ArrayList<Cars>();
car.setName("Hyundai");
car.setYear("2010");
car.setName("Maruti");
car.setYear("2010");
al.add(car)
我想用&#34; Hyundai&#34;添加另一个汽车对象。但是如果我的列表已经包含它,我想将我的名字改为Hyundai1,然后添加到列表中。
我试过用,
for(int i=0;i<al.size();i++)
{
boolean value = al.get(i).getName().contains("Hyundai");
}
if(value)
{
al.setName("Hyundai1");
}
else
{
al.setName("Hyundai");
}
注意:我对价值进行了硬编码&#34; Hyundai&#34;这里是为了让它更简单。请建议
答案 0 :(得分:1)
正如艾略特的建议:
public class Cars {
private String name;
private int year;
public String getName() {
return this.name;
}
@Override
public boolean equals(Object other){
if (other == null) return false;
if (other == this) return true;
if (!(other instanceof Cars)) return false;
// Check whether they are equivalent Strings or both null
Cars otherCar = (Cars) other;
if (this.name == null || otherCar.getName() == null) {
return this.name == otherCar.getName();
} else {
return this.name.equals(otherCar.getName()
}
}
// If two objects are equal, then they must have the same hash code.
@Override
public int hashCode() {
return this.name.hashCode();
}
}
答案 1 :(得分:1)
您的代码存在一些问题:
o1.entities[1]
声明之后没有class
,这主要用于方法。()
似乎是汽车的抽象,因此我将其命名为class
而不是Car
。Cars
在那里不可见,如果可以,它将具有value
中最后一辆车的值。所以你可能想在循环中行动。答案 2 :(得分:0)
查看您编写的代码,我相信您可能会尝试以下操作:
class Car{
public Car(){
this.createdCarNames = new ArrayList();
}
private String name;
private String year;
private ArrayList<String> createdCarNames;
/*The following method sets the name of the new Car object.
*It works by iterating over the list of created car names.
*If a car name in the list is found to be equal to that which
*you are attempting to set, concatenate a '1' to its end
*and set the name of the car object.
*Else, simply set the name of the Car object.
*Lastly, the name is added to the list of created car names.
*/
public void setName(String name){
for(String carName : createdCarNames){
if(carName.equals(name))
this.name = name.concat("1");
else this.name = name;
}
createdCarNames.add(name);
}
}
如果您不确定代码的任何部分,请随时指出。希望这会有所帮助。