在修剪/迁移期间检测阵列中的对象重复的问题

时间:2017-01-14 21:11:07

标签: java arrays object

我的程序后面应该接收一组对象,并根据特权变量的大小对它们进行排序。 “arrayFromBefore”变量填充了MyClass类型的对象。它只是基本上创建一个新的MyClass对象,并使用相同的对象属性返回它。

问题是,在某些情况下,优先级数组中似乎存在多个相同MyClass对象。这些重复也不总是相同的倍数(例如,一个对象连续出现3次,连续出现5次,另外两次等等)

MyClass[] priorityArray = new MyClass[arrayFromBefore.length];

for (int i = 0; i < priorityArray.length; i++) {
  int maxIndex = 0;
  int maxPrivilege = arrayFromBefore[i].returnPrivilege();
  for (int j = 1; j < arrayFromBefore.length; j++) {
    int currentPrivilege = arrayFromBefore[j].returnPrivilege();
    if (currentPrivilege > maxPrivilege) {
      maxPrivilege = currentPrivilege;
      maxIndex = j;
    }
  }
  MyClass mostPrivilaged = arrayFromBefore[maxIndex];
  priorityArray[i] = mostPrivileged;
  arrayFromBefore[maxIndex].setPriority(-900000000);
}

1 个答案:

答案 0 :(得分:1)

问题在于您的内部for-loop,其中每个ij从相同的值1开始。 j应该从i的下一个开始,因此无法覆盖相同的对象。

MyClass[] priorityArray = new MyClass[arrayFromBefore.length];
   for (int i=0; i<priorityArray.length - 1; i++) {
   int maxIndex = 0;
   int maxPrivilege = arrayFromBefore[i].returnPrivilege();
   for (int j=1+i; j<arrayFromBefore.legnth; j++) {
       int currentPrivilege = arrayFromBefore[j].returnPrivilege();
       if (currentPrivilege > maxPrivilege) {
           maxPrivilege = currentPrivilege;
           maxIndex = j;
       }
   }

// priorityArray[i] = mostPrivileged;  this line can be removed as it isn't required because you are getting sorted arrayFromBefore.  

myClass mostPrivilaged = arrayFromBefore[maxIndex];   // Swapping of        
arrayFromBefore[maxIndex] = arrayFromBefore[i];       // largest priority object
arrayFromBefore[i] = mostPrivilaged;                  // with its required position in sorted array.

}

在此之后,您将按优先级的降序缩短arrayFromBefore