我正在练习决赛,却遇到了这个问题-
给出以下代码,是否有实现类A的方式,以便最终在程序的一个运行中打印5,然后在程序的另一运行中打印5,然后再运行3 ...直到0。
可以假设它是确定性的,因此函数将始终产生相同的结果。
不能删除A类而非主类中的任何代码,而只能编辑A类。
public class A {
int i, j;
public A(int i, int j) {
this.i = i;
this.j = j;
}
public static void main(String[] args) {
Set<A> s = new LinkedHashSet<>();
s.add(new A(3,1));
s.add(new A(1,3));
s.add(new A(3,1));
s.add(new A(3,1));
s.add(new A(2,1));
System.out.println(s.size());
}
}
我正在考虑添加一种静态HASHMAP,每次创建一个对象时,我都会将其添加到该对象中,并检查一个键是否已存在,如果一个具有相同值,则我想“不创建”该对象已经存在...但是无法实现。
答案 0 :(得分:1)
您将要在类A中实现equals and hashcode。应以在将项添加到Set s
中时会引起冲突的方式实现它们。
默认情况下,它应该打印出数字5。
但是,如果我们进行以下修改:
public class A {
int i, j;
public A(int i, int j) {
this.i = i;
this.j = j;
}
@Override
public boolean equals(Object obj) {
// First we check if the object is null
// Then we check if it's the same class as this one
if(obj == null || obj.getClass()!= this.getClass()) {
return false;
}
A objectA = (A) obj;
if(this.i == objectA.i) {
return true;
} else {
return false;
}
}
@Override
public int hashCode()
{
return this.i;
}
此特定实现将导致打印出“ 3”。这是因为我们将其设置为使哈希码等于i
。因此,当我们向集合中添加类A
的两个实例时,它们将发生冲突。
在我们的例子中,当添加类A
的实例时,i的值为3, 1, 3, 3, 2
,i
有3个唯一值(3、1、2),因此因此它将打印3
。
从这里可以提出不同的实现方式以获得不同的值。