Charles Bell
Posts: 519
Nickname: charles
Registered: Feb, 2002
|
|
Re: simple problem but need help
|
Posted: Feb 23, 2003 9:03 AM
|
|
import java.util.*; public class VideoSorter{ public static void main(String[] args) { VideoSorter sorter = new VideoSorter(); int[] ids = {212, 17, 30, 461, 49, 15}; String[] titles= { "Necessary Roughness", "Top Gun", "Sleepless in Seattle", "Rudy", "One More", "Another One"}; List videos = new ArrayList(); /* Add Video objects to the List */ for (int i = 0; i < titles.length; i++){ Video video = new Video(ids[i], titles[i]); videos.add(video); } /* Display the list of Video objects before sort */ System.out.println("List before Sort"); for (int i = 0; i < titles.length; i++){ Video nextVideo = (Video) videos.get(i); System.out.println(nextVideo.toString()); } Collections.sort(videos, (Comparator)videos.get(0)); System.out.println("\nAfter Sort:"); for (int i = 0; i < titles.length; i++){ Video nextVideo = (Video) videos.get(i); System.out.println(nextVideo.toString()); } } static class Video implements Comparator{ private int id; private String title; public Video(int id, String title){ this.id = id; this.title = title; } public int getID(){ return id; } public String getTitle(){ return title; } public String toString(){ return "ID: " + String.valueOf(getID()) + "\t" + "Title: " + getTitle(); } public int compare(Object o1, Object o2){ Video video1 = (Video)o1; Video video2 = (Video)o2; return (new Integer(video1.getID())).compareTo(new Integer(video2.getID())); } public boolean equals(Object obj){ Video video = (Video)obj; return (new Integer(this.getID())).equals(new Integer(video.getID())); } } }
|
|