Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

I have an ArrayList filled with objects of the class result, each result has an attribute named value. I now want to create an Array which is filled with references to the same memory location as in the ArrayList but now in order where to object with the highest value is in the first location, the second highest in the second location and so forth.

I have searched here but haven't found any other post like it.

share|improve this question
6  
Why not just sort your current List Collections.sort(yourList, theComparator); mkyong.com/java/…, if you really need to keep the old, clone it first... then sort the new one.... – Petter Friberg Jan 2 at 14:56
    
docs.oracle.com/javase/tutorial/collections/interfaces/… is probably more useful than a mkyong page. – VGR Jan 2 at 15:30
    
@A.Bohlund What you asked is exactly what Comparators are for. Is your problem solved? – user3437460 Jan 2 at 19:48
    
@user3437460 No haven't solved it yet. Trying to get a compareTo to work, cant seem to make it work thou. – A.Bohlund Jan 2 at 21:40
    
@A.Bohlund check whether my solution for work for you – Narendra Jaggi Jan 3 at 4:14

There are multiple ways to solve it using Gauava or lambda expressions.

Hope this implementation solve your problem.

package com;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class TestDemo {


 public static void main(String[] args) {


  List < HockeyPlayer > players = new ArrayList < HockeyPlayer > ();
  HockeyPlayer obj1 = new HockeyPlayer();
  obj1.goalsScored = 22;
  players.add(obj1);
  HockeyPlayer obj2 = new HockeyPlayer();
  obj2.goalsScored = 11;
  players.add(obj2);
  HockeyPlayer obj3 = new HockeyPlayer();
  obj3.goalsScored = 111;
  players.add(obj3);
  HockeyPlayer obj4 = new HockeyPlayer();
  obj4.goalsScored = 3;
  players.add(obj4);

  Collections.sort(players, new Comparator < HockeyPlayer > () {
   @Override public int compare(HockeyPlayer player1, HockeyPlayer player2) {
    return player1.goalsScored - player2.goalsScored;
   }

  });

  for (int i = 0; i < players.size(); i++) {
   System.out.println(players.get(i).goalsScored);
  }

  HockeyPlayer array[] = new HockeyPlayer[players.size()];

  players.toArray(array); // contains reference 


  for (int i = 0; i < array.length; i++) {
   System.out.println(array[i].goalsScored);
  }


 }

}

class HockeyPlayer {
 public int goalsScored;

}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.