按字母顺序排列满对象的列表



拥有一个最多可容纳10个对象的数组,并希望在存储时,根据对象中的名称按字母顺序排列对象。问题是,它们不断地相互覆盖。我正在尝试制作一个键值数组,但不能使用任何映射函数或类似的函数。

public boolean add(ItemMoretti product) {
int i = findIndex(product.getName());
int j = 0;
boolean success = false;

if(mySize < myItems.length) {
for(j = (mySize - 1); j > i; j--) {
myItems[j + 1] = myItems[j];
}//for

myItems[i] = product;
mySize++;
success = true;
}//if
return success;
}//add

这里还有findIndex方法。

private int findIndex(String keyValue) {
int x = 0;
int index = -1;
boolean found = false;

while((x <= mySize) && (!found)) 
if((mySize == 0) || (myItems[x].getName().compareToIgnoreCase(keyValue) == 0)) {
index = x;
found = true;
}//if
else x++;

return index;   
}//findIndex

使用了bubbleSort算法。

private static ItemMoretti[] getSortedByName(ItemMoretti[] itemMorettis)
{
for (int i = 0; i < itemMorettis.length; i++)
{
boolean changed = false;
for (int j = 0; j < itemMorettis.length - 1; j++)
{
ItemMoretti o1 = itemMorettis[j];
ItemMoretti o2 = itemMorettis[j + 1];
if (o1.getName().compareTo(o2.getName()) > 0)
{
itemMorettis[j] = o2;
itemMorettis[j + 1] = o1;
changed = true;
}
}
if (!changed)
{
break;
}
}
return itemMorettis;
}

您使用的是一个数组,对于每个字母,都需要移位元素。因此,使用链表是一种有效的方法。

以下是如何使用它的示例:

public class ItemMorettiList {
private Node head;
private int size;
public ItemMorettiList() {
head = null;
size = 0;
}
public boolean add(ItemMoretti product) {
Node newNode = new Node(product);
Node current = head;
Node prev = null;
while (current != null && product.getName().compareToIgnoreCase(current.data.getName()) > 0) {
prev = current;
current = current.next;
}
if (prev == null) {
head = newNode;
} else {
prev.next = newNode;
}
newNode.next = current;
size++;
return true;
}
private class Node {
public ItemMoretti data;
public Node next;
public Node(ItemMoretti data) {
this.data = data;
this.next = null;
}
}
}

ItemMorettiList类使用Node对象来保持其链表的持续顺序。每个CCD_ 3保存一个CCD_。

add()方法负责遍历列表,以按字母顺序检测适当的位置,通过将新的Node放在最近的和即将到来的Node之间,将其附加到哪里。通过这种方式,该实现设法以固定和排序的顺序保留链表。