我创建了自己的数据结构,其功能类似于 ArrayDeque 并扩展了 AbstractList。其要点是保存其他数据结构,但不允许结构具有超过指定数量的元素。
例如(我的构造函数):
public MyD(Class<T> t, int limit)
{
}
其中 limit 确定添加到 ArrayDeque 的每个数据结构允许的元素数量。
我的问题是,因为我使用的是泛型,所以从技术上讲我不知道我当时正在使用什么类型的数据结构。
public void add(int i, T structure) {}
结构可以是数组、ArrayList、队列等任何内容。
我的问题:如果我知道它始终是某种形式的数据结构,是否有一种方法可以获取通用值并对其进行通用转换以获取其中的元素数量。
我尝试将其转换为简单的数组[],但如果传递列表,则会破坏功能。
@SuppressWarnings({"unchecked"})
T[] array = (T[])x;
if(array.length > b) { return; }
最佳答案
您可以使用一些反射来测试传递的结构是数组还是集合,然后相应地获取其大小:
public void add(int i, T structure) {
int size;
if (structure.getClass().isArray()) {
size = Array.getLength(structure);
} else if (structure instanceof Collection) {
size = ((Collection) structure).size();
} else {
throw new IllegalArgumentException("Structure is neither an array nor a collection");
}
if (size > limit) {
return;
}
// ...
}
关于java - 在不知道数据结构类型的情况下如何获取通用数据结构的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58161288/