-1

I have a list of linkedlist.

    List<LinkedList<File1>> lists = 
        Collections.synchronizedList(new ArrayList<LinkedList<File1>>());

each linkedlist contains objects of type File1.

class File1
{
    int dist,nod;       
}

Can anyone help me to sort the elements based on dist.

I thought of using collections.sort() but this cannot be used in this case, so can anyone suggest a better idea?

2
  • 3
    So you want to sort the inner lists only? Commented Apr 11, 2012 at 18:27
  • 1
    How did you figure out collections.sort() wont work, What is the reason behind? Commented Apr 11, 2012 at 19:20

3 Answers 3

6

Iterate over each linkedlist in your arraylist, then sort it. But to make sure that the elements are sorted on dist, you should implement Comparable:

public class File1 implements Comparable<File1>
{
    int dist, nod;

    public int compareTo(File1 f)
    {
        return Integer.compare(dist, f.dist);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

thnks a lot :) it was vry useful :)
@Divyashree: Welcome to StackOverflow. If someone answered your question that way that it solved your problem, you can accept the answer by hitting the tick under the score of the question. You will see that the tick will become green, this means you accepted the answer.
4

You could sort either the inner or outer lists using the Collections.sort() method that accepts a Comparator.

public static void sort(List list, Comparator c)

Comments

3

Use Collections.sort() with a custom comparator that compares the dist value of each object.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.