简体   繁体   中英

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).

presume I already have a MyClass[] array called input, that stores a finite amount of MyClass objects.

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".

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. It's also not even writing certain MyClass instances from the input array into the priorityArray array.

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. Of course element in priorityArray will have the same changes. To fix it you need to clone your object here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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