【问题标题】:Perform in-order(alphabetical) add in java array of objects在java对象数组中执行按顺序(按字母顺序)添加
【发布时间】:2017-02-12 05:12:10
【问题描述】:

我在下面有一段代码,只是将新元素添加到末尾,但我希望能够添加按目标名称按字母顺序排列的每个新元素。不确定我是否必须在添加后对列表进行排序,或者通过首先检查然后添加新对象来插入新对象。在任何一种情况下都不确定如何去做。

public void add()
    {
        int newRating =-1;
        in = new Scanner(System.in);
        if((lastElement+1) < MAX_ELEMENT)    //MAX_ELEMENT =100
        {
            System.out.print("Enter the Name: ");
            newDestination = in.nextLine();

            System.out.print("Enter the type of Vacation(Single character code: ");
            validCharacterCode();

            while(newRating < MIN_RATING || newRating > MAX_RATING)
            {
                System.out.print("Enter the Rating(1-5): ");
                newRating = in.nextInt();
            }
            lastElement++;
            aDestination[lastElement] = new Destination(newDestination,newVacationType,newRating);

       }
       else
       {
            System.out.print("Cannot add new elements: ");
            System.out.println("List already has " + MAX_ELEMENT + " elements.");
       } 
   }

【问题讨论】:

  • 如果你选择插入你的元素然后对结果数组进行排序,我推荐插入排序,它在列表已经接近排序时具有良好的性能(这就是你的列表)。
  • 如果您不想自己实现排序,可以查看Arrays.sort,但您必须实现Comparator
  • 谢谢,我想实现我自己的排序,插入排序听起来像我想要的。不过,我不知道该怎么做。我只是一个初学者,我考虑过遍历每个元素并检查每个目标值的第一个字符并进行相应的排序,但这听起来比它需要的复杂..我认为
  • 您可以在维基百科上查找插入排序。这篇文章有很好的伪代码说明它是如何工作的。

标签: java arrays sorting


【解决方案1】:

如果您决定使用Arrays.sort,则应遵循以下原则(包括使用 lambda 表达式的比较器函数示例):

    public void add()
    {
        String newDestination;
        int newRating =-1;
        in = new Scanner(System.in);
        if((lastElement+1) < MAX_ELEMENT)    //MAX_ELEMENT =100
        {
            System.out.print("Enter the Name: ");
            newDestination = in.nextLine();

            System.out.print("Enter the type of Vacation(Single character code: ");
            String newVacationType = in.nextLine();

            while(newRating < MIN_RATING || newRating > MAX_RATING)
            {
                System.out.print("Enter the Rating(1-5): ");
                newRating = in.nextInt();
            }
            lastElement++;

            aDestination[lastElement] = new Destination(newDestination,newVacationType,newRating);
            Arrays.sort(aDestination, 0, lastElement, (o1, o2) -> o1.destination.compareTo(o2.destination));

       }
       else
       {
            System.out.print("Cannot add new elements: ");
            System.out.println("List already has " + MAX_ELEMENT + " elements.");
       } 
   }

【讨论】:

    【解决方案2】:

    以特定顺序添加对象集合,这就是 PriorityQueue (Java Platform SE 7) 的用途。它保证了队列内的顺序。如果最后需要使用数组,可以随时转换回来。

    使用PriorityQueue&lt;Destination&gt; 代替Destination[]

    Comparator<Destination> byName = new Comparator<>(
    {
        @Override
        public int compare(Destination d1, Destination d2)
        {
            return d1.getName().compareTo(d2.getName());
        }
    });
    int initialCapacity = 10;
    PriorityQueue<Destination> destinationsByName = new PriorityQueue<>(initialCapacity, byName);
    

    现在,重构您的 add() 方法。使用此优先级队列进行插入,无需担心顺序,因为顺序由 destinationsByName 处理:

    public void add()
    {
        int newRating = -1;
        in = new Scanner(System.in);
        if ((lastElement+1) < MAX_ELEMENT)    //MAX_ELEMENT =100
        {
            ...
            Destination d = new Destination(...);
            destinationsByName.add(d);
            // no need to sort again
        }
        ...
    }
    

    如果你又需要一个数组怎么办?没问题,可以用下面的方法转回来:

    destinationsByName.toArray(new Destination[0]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-15
      • 1970-01-01
      • 2014-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      相关资源
      最近更新 更多