简体   繁体   English

根据变量将对象数组排序为另一个数组

[英]Sorting an object array into another array based on a variable

I have a problem with a program I'm writing for a school assignment.我正在为学校作业编写的程序有问题。 Essentially, before this piece of code, I already recieve and work with a bunch of information that I store into an array of objects.本质上,在这段代码之前,我已经接收并处理了存储到对象数组中的一堆信息。 Now I have to sort this array (after it's sorted, I will have to calculate some things in the order of the PRIORITY variable).现在我必须对这个数组进行排序(排序后,我必须按照 PRIORITY 变量的顺序计算一些东西)。

presume I already have a MyClass[] array called input, that stores a finite amount of MyClass objects.假设我已经有一个名为 input 的 MyClass[] 数组,它存储有限数量的 MyClass 对象。

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


}

the MyClass class if nothing fancy, but of course, contains a proper constructor, getter and setter methods and an integer variable "privilege". MyClass 类如果没什么特别的,当然,它包含一个适当的构造函数、getter 和 setter 方法以及一个整数变量“特权”。

I'm getting an error in my final tests of the program and, seeing as the program returns privileges as "-900000000", it has to have something to do with this part of the code.我在程序的最终测试中遇到错误,并且看到程序返回权限为“-900000000”,它必须与这部分代码有关。 It's also not even writing certain MyClass instances from the input array into the priorityArray array.它甚至没有将输入数组中的某些 MyClass 实例写入 priorityArray 数组。

How can I clead this up?我怎样才能解决这个问题? Help.帮助。

I'll rewrite my answer totally.我会完全重写我的答案。

In this line在这一行

priorityArray[i] = input[maxIndex];

You are assigning object from one array to another array by reference.您正在通过引用将对象从一个数组分配到另一个数组。 It means that there is only one object and you set value to -9000000 in the next line to it.这意味着只有一个对象并且您在它的下一行将值设置为 -9000000。 Of course element in priorityArray will have the same changes.当然,priorityArray 中的元素也会有相同的变化。 To fix it you need to clone your object here.要修复它,您需要在此处克隆您的对象。

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

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