The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
November 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Re: Another LinkedList problem...

Posted by Brian Sanders on November 08, 2001 at 12:48 PM

Sorry about the colors on the code listing. Here's a better listing of the same code:



import java.util.*;

public class List
{
//using actual Long values (rather than Strings) for simplicity
public static Object[][] DATA = {
{ "FirstItem", new Long(50) },
{ "SecondItem", new Long(10) },
{ "ThirdItem", new Long(80) },
{ "FourthItem", new Long(0) },
{ "FifthItem", new Long(10) }
};

/**
* Sorts the two lists. Preserves the relative order of two events happening at the same time.
*/
public static void main(String[] args)
{
//initializing the two linked list off of the data in the constant array
LinkedList names = new LinkedList();
LinkedList times = new LinkedList();

for (int i=0; i < DATA.length; i++)
{
names.add(DATA[i][0]);
times.add(DATA[i][1]);
}

//clone the array, and sort
LinkedList sortedTimes = (LinkedList) times.clone();
Collections.sort(sortedTimes);

//for each time in the sorted times list, find it's index in the unsorted times list.
//this can be used to find the corresponding element in the names list.
LinkedList sortedNames = new LinkedList();

//As we find an index for each time, replace it with a token object to indicate that it's already been used;
//this will allow for duplicate times. We clone the list b/c we assume preserving the original list is
//important.
Object BLANK = new Object();
LinkedList unsortedTimes = (LinkedList) times.clone();
for (Iterator i = sortedTimes.listIterator(); i.hasNext(); )
{
Long time = (Long) i.next();
int index = 0;
while (unsortedTimes.get(index) != time || unsortedTimes.get(index) == BLANK)
index++;
unsortedTimes.set(index, BLANK);
sortedNames.add(names.get(index));
}

//showing our results:
for (int i=0; i < sortedNames.size(); i++)
{
System.out.println(sortedNames.get(i) + ":" + sortedTimes.get(i));
}
}
}






Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us