我有下面的代码片段,只是将新元素添加到结尾但我希望能够按字母顺序添加按目的地名称排序的每个新元素。不确定我是否必须在添加后对列表进行排序,或者通过首先检查然后添加新对象来插入新对象。在任何一种情况下都不确定如何去做。
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.");
}
}
答案 0 :(得分: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.");
}
}
答案 1 :(得分:1)
按特定顺序添加对象集合,这是PriorityQueue (Java Platform SE 7)的用途。它保证队列中的顺序。如果你需要在最后使用一个数组,你总是可以将它转换回来。
使用PriorityQueue<Destination>
代替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]);