如何在Java中按字母顺序将对象添加到链接列表?

时间:2015-04-13 03:42:40

标签: java linked-list iterator compare add

我看到类似的问题,包括参数中的索引,但我的要求不允许我这样做。假设数组已按字母顺序排序。 这是我第一次问一个问题,如果我做错了就很抱歉。

public void addElement(Object element){
    LinkedListIterator iterator = new LinkedListIterator();
    int counter = 1;
    int compare = 0;
    if(first == null)
        iterator.add(element);
    else
    {
        while(iterator.hasNext())
        {
            compare = getElement(counter).toString().compareToIgnoreCase(element.toString());
//getElement is a method I made to retrieve an element from the linked list 
//I have tested it and I know it works. Its parameter is an index
//toString() returns a String of what the element is. example: { Fruit } 
//It is in that format with the brackets {}

            if(compare != -1)
                iterator.add(element);
            else
            {
                iterator.next();
                counter++;
            }
        }
    } 
}

1 个答案:

答案 0 :(得分:1)

根据您的问题,我并不确切知道您将其用作比较值。它是对象中的字符串值,对象引用的名称等吗?假设您基于某种名称变量插入对象,这就是您可以这样做的方法。

注意:我确定您可以找到适合您的某种现有方法/ api,但我假设您希望了解它是如何完成的。

对于这个例子,我创建了一个名为AnyObject的类来迭代和比较。它看起来像这样:

AnyObject类

public class AnyObject {

private String name;
private int num;
private String color;

public AnyObject(String name, int num, String color) {
    this.name = name;
    this.num = num;
    this.color = color;
}

@Override
public String toString() {
    return name;
}

}

使用这个简单的类,我们会修改你的代码,使它看起来像这样:

AlphaInsertSort类

import java.util.*;

public class AlphaInsertSort {

public static void main(String[] args) {
    ArrayList<AnyObject> myList = new ArrayList<AnyObject>();
    myList.add(new AnyObject("alphaObj", 44, "blue"));
    myList.add(new AnyObject("betaObj", 7, "orange"));
    myList.add(new AnyObject("gammaObj", 12, "red"));
    myList.add(new AnyObject("omegaObj", 99, "yellow"));
    printList(myList); //helps visualize what's going on
    addElement(new AnyObject("charlieObj", 105, "purple"), myList);
    printList(myList);
    addElement(new AnyObject("aObj", 105, "purple"), myList);
    printList(myList);

    myList.add(new AnyObject("thetaObj", 0, "green"));
    printList(myList);
    addElement(new AnyObject("zetaObj", 2, "pink"), myList);
    printList(myList);
    System.out.println("Finished");
}

public static void addElement(AnyObject element, ArrayList<AnyObject> myList){
    ListIterator<AnyObject> iterator = null;
    //int counter = 1; don't need this
    int compare = 0;
    AnyObject current = myList.get(0); //changed name from first to current and will use this for comparison while iterating
    iterator = myList.listIterator(); //this should set iterator to start of list. There's no constructor for listIterator

    System.out.println("\ncurrent is " + current.toString());

    if(current == null)
        iterator.add(element);
    else
    {

        while(iterator.hasNext())
        {
            //compare = getElement(counter).toString().compareToIgnoreCase(element.toString());
            compare = current.toString().compareToIgnoreCase(element.toString());

            //for display purposes
            System.out.println(current.toString() + " compared to " + element.toString() + " is " + current.toString().compareToIgnoreCase(element.toString()));

            if(compare > 0) { //want to add element into list if compare is negative. Won't necessarily be -1
                iterator.previous(); //will need to move back a spot before adding. Otherwise will always add element after first encountered element that doesn't come before element inserting
                iterator.add(element);
                break; //make sure to break.  No need to continue iterating
            }
            else
            {
                current = iterator.next();
                //counter++;
            }
        }

        //if element is larger than all existing elements in list
        if(!myList.contains(element)) {
            iterator.add(element);
        }
    } 
}

public static void printList(ArrayList<AnyObject> myList) {
    System.out.println("List contents:");
    for(AnyObject element : myList) {
        System.out.println(element.toString());
    }
    System.out.println();
}
}

我删除了计数器int因为你在说明书中提到你没有选择使用索引,所以包含它并没有意义。还值得注意的是compareTo和compareToIgnoreCase不一定返回-1和1.它可以返回任何正值和负值,因此更改条件将是明智的。此外,如果调用方法的值小于要与之比较的值,则compareTo返回一个负数,因此您希望停止迭代并在比较为负时添加该值。此外,由于您没有迭代器在您列表中当前位置之前的1个元素,因此当比较返回负整数时,您需要将迭代器移回1个元素。如果您不这样做,您的新元素将始终在按字母顺序排在第一个元素之后立即添加。这是因为您无法在迭代器之后立即看到下一个元素。这有意义吗?

例如,如果你有一个1,2,4,5的列表,并且你想要为它添加3,你可以比较1到3,2到3,然后是4到3.当你的迭代器达到2时,它不知道下一个值是什么。由于3大于2,它移动到4. 4小于3,因此add(3)被调用。然而,这将元素与元素(4)进行比较后放置3。您的列表将是1,2,4,3,5。解决此问题的最简单方法是调用iterator.previous();紧接在iterator.add(3)之前;

如果您想进一步澄清,请与我们联系。