我的问题就像标题所说:我想检测并防止ArrayList中的重复名称。我不能使用任何Set方法。
这是我的代码:
private static void kommandoEtt() {
Kund nyKund = new Kund();
System.out.print("Name: ");
nyKund.setNamn(tangentbord.nextLine());
kundregister.add(nyKund);
}
答案 0 :(得分:3)
不使用Set
,您可以避免使用List
方法向List#contains(Object)
添加两个相同的对象。
示例:
List<String> strings = new ArrayList<String>();
if (!list.contains("mystring"))
System.out.println("added string? "+list.add("mystring"));
if (!list.contains("mystring"))
System.out.println("added string? "+list.add("mystring"));
输出:
added string? true
added string? false
<强>陷阱强>
上述方法适用于基本Java原语,例如String
,Double
,Integer
,...等。如果您有自己的对象,则需要覆盖{{你班级的1}}和hashCode
方法。否则,equals
方法将根据对象的地址而不是内容来测试相等性。
错误的例子:
List#contains
输出:
public class Fraction {
int x, int y;
public Fraction(int x, int y) { this.x=x;this.y=y;}
}
List<Fraction> fractions = new ArrayList<Fraction>();
Fraction f1 = new Fraction(1,2);
if (!fractions.contains(f1))
System.out.println("added fraction? "+fractions.add(f1));
if (!fractions.contains(f1))
System.out.println("added fraction? "+fractions.add(f1));
修复示例:
added fraction? true
added fraction? true
输出:
public class Fraction {
public int x, int y;
public Fraction(int x, int y) { this.x=x;this.y=y;}
@Override
public boolean equals(Object o) {
if (o==null) return false;
if (o==this) return true;
if (!(o instanceof Fraction) return false;
Fraction f = (Fraction) o;
return f.x == x && f.y ==y;
}
}
List<Fraction> fractions = new ArrayList<Fraction>();
Fraction f1 = new Fraction(1,2);
if (!fractions.contains(f1))
System.out.println("added fraction? "+fractions.add(f1));
if (!fractions.contains(f1))
System.out.println("added fraction? "+fractions.add(f1));
答案 1 :(得分:0)
向容器添加内容而不重复的另一种方法是使用Set。如果您需要保持相同的顺序,您可以使用LinkedHashSet实现。
然后你需要在你的类中实现一个equals方法来检查这些项是否是类似的。
在你的情况下,我猜这个名字可能是不同的价值。然后可以实现等于:
public boolean equals(Object o) {
// if the object you compare to isn't Kund then they aren't equal.
if(!(o instanceof Kund)) return false;
// return the value of the equals between this object and the object you want
// to check equality on. And use the objects name as the field determining if
// the values are equal.
return this.getName().equalsIgnoreCase((Kund)o.getName());
}
public int hashCode() {
return this.getName().hashCode();
}
您还需要为对象实现hashCode函数,以便它在hashset中获取特定位置,以供标准java实现进行查找。