Java Bag 数据结构实现及测试代码示例
Java Bag 数据结构实现及测试代码示例
本示例展示了 Java 中 Bag 数据结构的简单实现,以及使用 main 函数进行测试的代码。
Bag 类实现
import java.util.Objects;
import java.util.Random;
public class Bag {
private Object[] items; // 用于存储物品的数组
private int size; // 记录物品数量
public Bag() {
items = new Object[100]; // 创建一个最多可容纳100个物品的空袋
size = 0; // 初始物品数量为0
}
// 将项目添加到此袋子列表项目的末端
public void insert(Object item) {
if (size >= items.length) {
throw new RuntimeException("Bag is full"); // 如果袋子已满,则抛出异常
}
items[size] = item; // 将项目添加到末端
size++; // 物品数量增加
}
// 移除此袋末端的物品
public void removeLast() {
if (size == 0) {
throw new RuntimeException("Bag is empty"); // 如果袋子为空,则抛出异常
}
items[size-1] = null; // 将末端物品置为空
size--; // 物品数量减少
}
// 按随机索引从此Bag中删除项目
public void removeRandom() {
if (size == 0) {
throw new RuntimeException("Bag is empty"); // 如果袋子为空,则抛出异常
}
Random random = new Random();
int randomIndex = random.nextInt(size); // 生成一个随机索引
items[randomIndex] = items[size-1]; // 将随机索引处的物品替换为末端物品
items[size-1] = null; // 将末端物品置为空
size--; // 物品数量减少
}
// 从这个包中获取一个项目的第一个匹配项的索引
public int get(Object item) {
for (int i = 0; i < size; i++) {
if (Objects.equals(item, items[i])) {
return i; // 返回第一个匹配项的索引
}
}
return -1; // 如果找不到匹配项,则返回-1
}
// 获取对位于此袋的位置索引处的项目的引用
public Object get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index out of bounds"); // 如果索引超出界限,则抛出异常
}
return items[index]; // 返回索引处的项目
}
// 返回此袋子尺寸中的物品数量
public int size() {
return size;
}
// 检查这个袋子是否是空的
public boolean isEmpty() {
return size == 0;
}
// 清空这个袋子
public void makeEmpty() {
for (int i = 0; i < size; i++) {
items[i] = null; // 将所有物品置为空
}
size = 0; // 物品数量归零
}
}
// IndexOutOfBoundException的子类,用于表示索引超出界限的异常
class IndexOutOfBoundsException extends RuntimeException {
public IndexOutOfBoundsException(String message) {
super(message);
}
}
### 测试 `main` 函数
```java
public class Main {
public static void main(String[] args) {
Bag bag = new Bag();
// 测试插入物品
bag.insert("item1");
bag.insert("item2");
bag.insert("item3");
System.out.println("Bag size: " + bag.size()); // 预期输出: 3
// 测试获取物品的索引和引用
int index = bag.get("item2");
System.out.println("Index of 'item2': " + index); // 预期输出: 1
Object item = bag.get(index);
System.out.println("Item at index " + index + ": " + item); // 预期输出: item2
// 测试移除物品
bag.removeRandom();
System.out.println("Bag size after removing a random item: " + bag.size()); // 预期输出: 2
bag.removeLast();
System.out.println("Bag size after removing the last item: " + bag.size()); // 预期输出: 1
// 测试清空袋子和判空
bag.makeEmpty();
System.out.println("Is bag empty? " + bag.isEmpty()); // 预期输出: true
}
}
运行以上 main 函数会进行一系列的测试操作,并输出相应的结果。您可以根据需要自行修改 main 函数中的测试代码。
总结
本示例展示了 Java Bag 数据结构的基本实现和测试方法,您可以根据需要进行修改和扩展。
原文地址: https://www.cveoy.top/t/topic/V09 著作权归作者所有。请勿转载和采集!