简体   繁体   English

移动对象数组中的元素

[英]Shifting elements in an Array of objects

I need to insert an Appointment in a Planner class that takes Appointment A1 as a parameter and places A1 in proper order to an array Appoint.我需要在 Planner 类中插入一个约会,该类将约会 A1 作为参数并将 A1 按正确顺序放置到数组约会中。 I have already created the Array which only has 4 default appointments and has a length of 20. I also created a method to compare two objects of the Array and return true if A1 is smaller than A2.我已经创建了只有 4 个默认约会且长度为 20 的 Array。我还创建了一个方法来比较 Array 的两个对象,如果 A1 小于 A2,则返回 true。 I have a method which allows me to insert info into the Array if array[i{ = null.我有一个方法,如果 array[i{ = null. However I have no idea how to sort it as I have to shift elements not sort the entire array但是我不知道如何对其进行排序,因为我必须移动元素而不是对整个数组进行排序

As I have learned to code and taken more classes I've realized the answer.随着我学会了编码并参加了更多的课程,我已经意识到了答案。 The array of appointments needs to be a String array and as you move into inserting new appointments compare the first three letters, then the numbers, then years.约会数组需要是一个字符串数组,当您开始插入新约会时,比较前三个字母,然后是数字,然后是年份。 At the time I used a huge nested if else loop.当时我使用了一个巨大的嵌套 if else 循环。 As each date is a set amount of letters (3 for month, 2 day, 4 year) it is quite simple and simply push the other dates down if needed.由于每个日期都是一定数量的字母(3 个表示月、2 天、4 年),因此非常简单,如果需要,只需将其他日期推下即可。 Although I believe for this project the dates it never went above 20, I would put an error message so the code doesn't crash when being tested.虽然我相信这个项目的日期从未超过 20,但我会发布一条错误消息,以便代码在测试时不会崩溃。

You'd better use a PriorityQueue instead of an Array .您最好使用PriorityQueue而不是Array The PriorityQueue is based on a priority heap, once you add an element it will be shifted up/down the tree which takes O(log(N)) time complexity. PriorityQueue基于优先级堆,一旦添加元素,它将在树中向上/向下移动,这需要 O(log(N)) 时间复杂度。 If you shift an element in Array, it will take O(N).如果您在 Array 中移动一个元素,它将花费 O(N)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM