1. 重写对象的equals
以ShopItem为例
public class ShopItem {
private String name;
private double price;
public ShopItem(String name, double price) {
this.name = name;
this.price = price;
}
}
ShopItem由两个成员变量name和price组成,
以equals方法为例
注:
- 基本数据类型,使用其包装类比较
- 对象使用Objects.equals比较
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (other == null || getClass() != other.getClass()) return false;
ShopItem shopItem = (ShopItem) other;
return Double.compare(shopItem.price, price) == 0 &&
Objects.equals(name, shopItem.name);
}
2. 重写hashcode方法
使用 Objects.hash方法计算hash值
注意:
@Override
public int hashCode() {
return Objects.hash(name, price);
}
hashcode的算法有很多总,jdk中采用的算法是如下
public static int hashCode(Object a[]) {
if (a == null)
return 0;
int result = 1;
for (Object element : a)
result = 31 * result + (element == null ? 0 : element.hashCode());
return result;
}
2.插入删除等算法
2.0 扩容
public void resize() {
if (count+1 >= shoppingItems.length) {
ShoppingItem[] tempShoppingItems = new ShoppingItem[shoppingItems.length * 2];
for (int i = 0; i < count; i++) {
tempShoppingItems[i] = shoppingItems[i];
}
shoppingItems = tempShoppingItems;
}
}
2.1 插入
public void insert(ShoppingItem item, int index) {
if (index < 0 || index >= size()) {
return;
}
resize();
for (int i = size() - 1; i >= index; i--) {
shoppingItems[i + 1] = shoppingItems[i];
}
shoppingItems[index] = item;
count++;
}
public void append(ShoppingItem item) {
insert(item, (size()-1));
}
public void prepend(ShoppingItem item) {
insert(item, 0);
}
2.3删除
public ShoppingItem deleteItemAt(int index) {
if (index < 0 || index >= size()) {
return null;
} else {
ShoppingItem deleteShoppingItem = get(index);
for (int i = index; i < size() - 1; i++) {
shoppingItems[i] = shoppingItems[i + 1];
}
shoppingItems[size() - 1] = null;
count--;
return deleteShoppingItem;
}
}
public ShoppingItem deleteItem(String name) {
for (int i = 0; i < size() - 1; i++) {
ShoppingItem shoppingItem = shoppingItems[i];
if (Objects.equals(name, shoppingItem.getName())) {
return deleteItemAt(i);
}
}
return null;
}