0

I have the piece of code below which as it is, just adds the new element to the end but i want to be able to add each new element ordered in alphabetical order by the Destination name. Not sure if i would have to sort the list after addition or insert the new object by first checking and then adding it. In either case not sure how to go about doing it.

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.");
       } 
   }
4
  • If you choose to insert your element and then sort the resulting array, I'd recommend insertion sort, which has good performance when the list already nearly sorted (which is what your list would be). Commented Feb 12, 2017 at 5:17
  • If you don't want to implement a sort yourself, you can look into Arrays.sort, but you will have to implement a Comparator. Commented Feb 12, 2017 at 5:21
  • Thanks, I want to implement the sort my self and the insertion sort sounds like what I'm going for. Im not sure how to go about this however. I'm only a beginner and Ive thought about going through each element and checking first characters of each destination value and sorting accordingly but it sounds way complicated than it needs to be..i think Commented Feb 12, 2017 at 5:36
  • You can look up insertion sort on Wikipedia. The article has pretty good pseudo-code on how it works. Commented Feb 12, 2017 at 5:46

2 Answers 2

1

If you decide to use Arrays.sort, it should be along these lines (includes example of comparator function using a lambda expression):

    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.");
       } 
   }
Sign up to request clarification or add additional context in comments.

Comments

1

Adding a collection of objects in a specific order, that's what the PriorityQueue (Java Platform SE 7) is made for. It guarantees the order inside the queue. If you need to use an array at the end, you can always convert it back.

Use PriorityQueue<Destination> instead of 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);

Now, refactor your add() method. Use this priority queue for insertion without worrying the order since order is taken care by 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
    }
    ...
}

What if you need an array again? No problem, you can use the following method to convert it back:

destinationsByName.toArray(new Destination[0]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.