Preciso remover um elemento da matriz com base em uma correspondência. Aqui está meu método para remover o evento.
public boolean removeEvent(int year, int month, int day, int start, int end, String activity)
{
Event newEvent = new Event(year, month, day, start, end, activity);
for (int i = 0; i < 5; i++)
{
if (newEvent.equals(events[i]))
{
events[i] = null;
newEvent = null;
numEvents--;
}
}
Quando eu tento
calendarTest1.removeEvent(2000, 1, 1, 1, 1, "Cal Test 1");
nada acontece. Eu tenho um elemento em minha matriz com esses valores, mas não altera esse elemento para nulo.
Isso é para lição de casa, então eu realmente não quero que me digam como fazer, apenas por que isso não funciona. Obrigado.
Aqui está meu método de igualdade:
public boolean equals(Object obj){
Event someEvent = (Event) obj;
if(
this.date == someEvent.date
&&
this.start == someEvent.start
&&
this.end == someEvent.end
&&
this.activity.equals(someEvent.activity))
if(obj == null)
return false;
if(obj instanceof Event)
return true;
else
{
return false;
}
}
Eu tentei muitas coisas diferentes, mas ainda recebo o erro NullPointerException
Respostas:
0 para resposta № 1seu método igual substituído deve ser algo como abaixo
@Override
public boolean equals(Object o) {
// If the object is compared with itself then return true
if (o == this) {
return true;
}
/* Check if o is an instance of Event or not
"null instanceof [type]" also returns false */
if (!(o instanceof Event)) {
return false;
}
// typecast o to Event so that we can compare data members
Event e = (Event) o;
// Compare the data members and return accordingly
return year==e.year && month== e.month && day==e.day && start == e.start && end == e.end && activity.equals(e.activity);
}
}
0 para resposta № 2
Você está comparando duas instâncias neste se event[i]
tem Event
instância, então a forma de comparação é diferente da comparação de strings.
Você precisa substituir equals
método em sua classe ex:
@Override
public boolean equals(Object ob) {
if (ob == null)
return false;
if (ob instanceof Event) {
Event e = (Event)ob;
return this.someStringValue.equals(e.someStringValueItHas); // compare all values you want like this
}
return false;
}
aqui verificamos a instância correta da classe e suas propriedades se são iguais ou não.
0 para resposta № 3
seu método equals está verificando todos os atributos?
public boolean equals(Object o){
if(o == null) return false;
if(o instanceOf Event){
Event givenObject = (Event) o;
if(this.year == givenObject.year)
if(this.month == givenObject.month)
.....
.....
if(this.activity.equals(givenObject.activity)){
return true;
}
}
return false;
}