|
-
September 14th, 2005, 04:22 PM
#1
ArrayList Sorting
Hello all,
I have been looking around for info on sorting ArrayLists and have found a bit, but I am still kinda stuck.
Given this:
Code:
for (int count = 0; count < numb.size(); count++)
{
System.out.println(numb.get(count));
}
System.out.println("______SORTED OUTPUT______");
//Now that we have an array list full of file data, lets sort it
Collections.sort(numb);
System.out.println("array len is "+numb.size());
for (int count = 0; count < numb.size(); count++)
{
System.out.println(numb.get(count));
}
How exactly do I do a numeric value sort? I think it involves creating a comparator, but I have not found anything that explains it in a way that I can wrap my hands around it.
What the program does is read in some numbers into an ArrayList (numb) and print the list, then sort, then print again.
My output looks like this right now:
40
20
60
10
50
70
100
90
80
______SORTED OUTPUT______
array len is 9
10
100
20
40
50
60
70
80
90
Collections.sort(numb) does sort, but not by numeric value. the sorted output should be this:
10
20
40
50
60
70
80
90
100
I used an ArrayList because the number of user entered numbers is variable.
Any ideas? would it work better to feed the ArrayList into an Array based on the size of the list, then use Array.sort() on it? or would it be easier to come up with a comparator?
And can someone give me a simple expanation of how that works? I have not come across anything like this before, and I have no idea how to write a comparator or even what one looks like...
Thanks
Jeff
-
September 14th, 2005, 06:37 PM
#2
Re: ArrayList Sorting
That is most likely happening because you're storing the data as String's. Instead, convert it to integers using Integer.parseInt() before adding it to the ArrayList:
Code:
BufferedReader inReader = .....;
String input;
while ((input = inReader.readLine()) != null)
numb.add(Integer.parseInt(input));
Incidentally, you should prefer using iterator's to traverse a container rather then using get:
Code:
Iterator i = numb.iterator();
while (i.hasNext())
System.out.println(i);
or use the new enhanced for loop in Java 1.5:
Code:
for (int i : num)
System.out.println(i);
Hungarian notation, reinterpreted? http://www.joelonsoftware.com/articles/Wrong.html
-
September 14th, 2005, 06:59 PM
#3
Re: ArrayList Sorting
CMA,
Thanks for the reply... Let be expand a bit before I go farther... Yes, I am taking this as a class... No I dont want anyone doing my projects for me. I like to code, I enjoy it, I just need a kick in the right direction from time to time when I am doing something new.
For what its worth, I am taking this class as an Independent Study due to work conflicts, so I dont have any "real" access to the instructor. Basically, I just work my way though the book, turn in some projects, and thats it. So I have to rely on google and places like codeguru for help when I get stuck.
Now that I have the disclaimer out of the way again, thanks for the reply. I have some questions that just occured to me:
In your first bit of code, you wrote pretty much the same thing I did for populating the ArrayList, only once I stared looking at string conversions I used Long.parseLong because I dont know that the files I will be given will contain only integers. They could contain anything... And now that I just said that, I should change that to float instead... doh!
Anyway, what I wanted to ask you about was this:
Code:
BufferedReader inReader = .....;
the full program uses a JFileChooser to allow the user to select a text file to be read. It takes the chooser.getFileName() return and puts that in a File called infile. Then a scanner opens infile and uses scan.getNext() to read each line to the end.
Is there a difference in performance/security/whatever in using BufferedReader over a Scanner for something simple like this? I ran across a blurb mentioning BufferedReader, but since the scanner was working for me, I didnt dig into it at that time. I am guessing that a BufferedReader would be far better (just guessing from the class name) if the file is large.
I also noticed that when I first wrote the code for the scanner, I could not get it to compile. It errored out with a FileNotFound exception, and the only way I could get the app to compile was to write an exception handler to trap the FNF exception that was being thrown. Would switching that to a BufferedReader fix that?
Thanks also for the pointer to the iterator. I saw that referenced in some stuff I was reading earlier, but I couldnt find a good explanation of what an iterator was, how it worked, or how to properly invoke or use it. Thats another thing for me to look more in to tonight.
And also thanks for the info on the enhanced loop. Thats a whole lot neater than the C++ way of doing it. I am using the Sun J2EE jdk to develop, but the book I have to use for the class is based on an older version of J2SE, and I am finding that there are some differences here and there. The loop you demonstrated is one of those.
Anyway, Thanks for the kick in the right direction. Im gonna go fire up the laptop and get back to work on the project and see if I can get the rest of it done tonight.
Cheers
Jeff
-
September 14th, 2005, 10:12 PM
#4
Re: ArrayList Sorting
 Originally Posted by bladernr
Is there a difference in performance/security/whatever in using BufferedReader over a Scanner for something simple like this? I ran across a blurb mentioning BufferedReader, but since the scanner was working for me, I didnt dig into it at that time. I am guessing that a BufferedReader would be far better (just guessing from the class name) if the file is large.
In terms of this example, no, there shouldn't be any huge performance difference. The Scanner class is actually a new class that they added to the latest version of Java. I'm guessing many course's now-a-days are now switching over to using the Scanner class for teaching basic input rather then traditional BufferedReader because using BufferedReader requires an early introduction to exception handling.
I also noticed that when I first wrote the code for the scanner, I could not get it to compile. It errored out with a FileNotFound exception, and the only way I could get the app to compile was to write an exception handler to trap the FNF exception that was being thrown. Would switching that to a BufferedReader fix that?
FileNotFoundException is a checked exception, meaning you have to either handle it or declare it to be thrown. Switching over to BufferedReader, you would still have to handle the more general IOException, from which FileNotFoundException derives from.
Thanks also for the pointer to the iterator. I saw that referenced in some stuff I was reading earlier, but I couldnt find a good explanation of what an iterator was, how it worked, or how to properly invoke or use it. Thats another thing for me to look more in to tonight.
An iterator just abstracts the notion of a position in a container. Depending on the List container that you use, using get() over an iterator can have serious performance issues.
And also thanks for the info on the enhanced loop. Thats a whole lot neater than the C++ way of doing it. I am using the Sun J2EE jdk to develop, but the book I have to use for the class is based on an older version of J2SE, and I am finding that there are some differences here and there. The loop you demonstrated is one of those.
The enhanced for loop is part of the new features from Java 1.5. Many books are still being updated to reflect the new stuff.
Hungarian notation, reinterpreted? http://www.joelonsoftware.com/articles/Wrong.html
-
September 15th, 2005, 01:59 AM
#5
Re: ArrayList Sorting
 Originally Posted by bladernr
Hello all,
How exactly do I do a numeric value sort? I think it involves creating a comparator, but I have not found anything that explains it in a way that I can wrap my hands around it.
Here's an example to get you started
Code:
import java.util.*;
public class Numbers
{
private long num;
public Numbers(long num)
{
this.num = num;
}
public Long getNumber()
{
return num;
}
public String toString()
{
return String.valueOf(num);
}
public static void main(String[] args)
{
ArrayList list = new ArrayList();
long multiplier = 10;
for(int i=0; i<10; i++)
{
list.add(new Numbers(i * multiplier));
multiplier = multiplier * 10;
}
System.out.println("Original order\n--------------");
for(int i=0; i<list.size(); i++)
{
System.out.println((Numbers)list.get(i));
}
Collections.shuffle(list);
System.out.println("\nShuffle list\n--------------");
for(int i=0; i<list.size(); i++)
{
System.out.println((Numbers)list.get(i));
}
Collections.sort(list, new Sort.ByNumberAscending());
System.out.println("\nList Ascending\n--------------");
for(int i=0; i<list.size(); i++)
{
System.out.println((Numbers)list.get(i));
}
Collections.sort(list, new Sort.ByNumberDescending());
System.out.println("\nList Descending\n--------------");
for(int i=0; i<list.size(); i++)
{
System.out.println((Numbers)list.get(i));
}
Collections.sort(list, new Sort.ByStringLengthAscending());
System.out.println("\nList arrange by string length ascending\n--------------");
for(int i=0; i<list.size(); i++)
{
System.out.println((Numbers)list.get(i));
}
Collections.sort(list, new Sort.ByStringLengthDescending());
System.out.println("\nList arrange by string length descending\n--------------");
for(int i=0; i<list.size(); i++)
{
System.out.println((Numbers)list.get(i));
}
}
}
class Sort
{
public static class ByNumberAscending implements Comparator
{
public int compare(Object object1, Object object2)
{
Numbers num1 = (Numbers) object1;
Numbers num2 = (Numbers) object2;
Long i1 = num1.getNumber();
Long i2 = num2.getNumber();
return i1.compareTo(i2);
}
}
public static class ByNumberDescending implements Comparator
{
public int compare(Object object1, Object object2)
{
Numbers num1 = (Numbers) object1;
Numbers num2 = (Numbers) object2;
Long i1 = num1.getNumber();
Long i2 = num2.getNumber();
return i2.compareTo(i1);
}
}
public static class ByStringLengthAscending implements Comparator
{
public int compare(Object object1, Object object2)
{
Numbers num1 = (Numbers) object1;
Numbers num2 = (Numbers) object2;
Integer s1 = num1.toString().length();
Integer s2 = num2.toString().length();
return s1 - s2;
}
}
public static class ByStringLengthDescending implements Comparator
{
public int compare(Object object1, Object object2)
{
Numbers num1 = (Numbers) object1;
Numbers num2 = (Numbers) object2;
Integer s1 = num1.toString().length();
Integer s2 = num2.toString().length();
return s2 - s1;
}
}
}
Output:
Original order
--------------
0
100
2000
30000
400000
5000000
60000000
700000000
8000000000
90000000000
Shuffle list
--------------
2000
100
60000000
90000000000
700000000
5000000
400000
8000000000
0
30000
List Ascending
--------------
0
100
2000
30000
400000
5000000
60000000
700000000
8000000000
90000000000
List Descending
--------------
90000000000
8000000000
700000000
60000000
5000000
400000
30000
2000
100
0
List arrange by string length ascending
--------------
0
100
2000
30000
400000
5000000
60000000
700000000
8000000000
90000000000
List arrange by string length descending
--------------
90000000000
8000000000
700000000
60000000
5000000
400000
30000
2000
100
0
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|