gpt4 book ai didi

java - 在 java 对象数组中执行按顺序(按字母顺序)添加

转载 作者:行者123 更新时间:2023-12-02 03:02:52 26 4
gpt4 key购买 nike

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

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,则应遵循以下原则(包括使用 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.");
}
}

关于java - 在 java 对象数组中执行按顺序(按字母顺序)添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42184427/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com