Java 双链表数组
我想创建一个数组,其中每个元素都是一个双链接列表。以下是我目前掌握的情况:Java 双链表数组,java,arrays,data-structures,linked-list,doubly-linked-list,Java,Arrays,Data Structures,Linked List,Doubly Linked List,我想创建一个数组,其中每个元素都是一个双链接列表。以下是我目前掌握的情况: public ArrayOfLists() { this.limit = limit; //limit of Nodes in each element of listArray listArray = (DoublyLinkedList<E>[]) new DoublyLinkedList[3]; listArray[0] = new DoublyLinkedList<E&g
public ArrayOfLists() {
this.limit = limit; //limit of Nodes in each element of listArray
listArray = (DoublyLinkedList<E>[]) new DoublyLinkedList[3];
listArray[0] = new DoublyLinkedList<E>();
listArray[1] = new DoublyLinkedList<E>();
listArray[2] = new DoublyLinkedList<E>();
size = 0;
}
我是否可以访问我的doublyLinkedList类中已经实现的方法来帮助实现这一点?非常感谢你 我不确定您将使用什么逻辑来确定要将
obj
添加到阵列的哪个插槽,但这就是您将如何操作(在实现calculateArraySlotSomehow
后,当然):
根据您的评论,您可以实现如下内容:
private int calculateArraySlotSomehow(E obj)
{
// 'count' is the total number of elements that are already
// stored in this data structure
// 'size' is the number of array elements
// 'limit' is the number of elements per list
int slot = count / limit;
if (slot >= size) {
throw new IndexOutOfBoundsException("Index: " + slot + ", Size: " + size);
}
return slot;
}
然后您必须将添加实现更改为:
public void add(E obj)
{
int index = calculateArraySlotSomehow(obj);
listArray[index].add(obj);
count++;
}
请注意,这不是线程安全的
我很好奇你到底想完成什么,因为我觉得你可能会不遗余力地把事情复杂化。为什么不使用双链接列表呢?您可以通过listOfLists.add(双链接列表e)访问它们
,listOfList.get(idx.add)(E)
,listOfLists.get(idx)//返回DublyLinkedList
,列表。get(idx1)。get(idx2);//返回一个元素
,…这很有意义。如何计算阵列插槽?我有一个int-size(数组的大小)和一个int-limit(双链表的大小)。我会假设一堆条件来检查我是否添加了超出这些界限的内容?
private int calculateArraySlotSomehow(E obj)
{
// 'count' is the total number of elements that are already
// stored in this data structure
// 'size' is the number of array elements
// 'limit' is the number of elements per list
int slot = count / limit;
if (slot >= size) {
throw new IndexOutOfBoundsException("Index: " + slot + ", Size: " + size);
}
return slot;
}
public void add(E obj)
{
int index = calculateArraySlotSomehow(obj);
listArray[index].add(obj);
count++;
}