简体   繁体   中英

Sorting lists with one instance

Hello I am trying to pass to my jsp page two sorted Lists which I get from the database like that

   @RequestMapping(value = "/sortDate", method= RequestMethod.GET)
  public void sortedLists(Model model, HttpSession session){


    List<Song> songsByDate;
    try {
    songsByDate = SongDAO.getInstance().getAllSongs();
    Collections.sort(songsByDate, new UploadTimeComparator());
    session.setAttribute("songs", songsByDate);
     /////////////////////////////////
    List<Song> songsByLikes;
    try {
        songsByLikes = SongDAO.getInstance().getAllSongs();
    Collections.sort(songsByLikes, new LikesComparator());
    session.setAttribute("songs2", songsByLikes);
   }}}

However the problem is since I use getInstance() , songs and songs2 are the same Lists sorted by Likes,how can I overcome this problem?

You need to copy each "all songs" list to a new array list, which you can then proceed to sort.

So:

List<Song> songsByDate = new ArrayList<>( SongDAO.getInstance().getAllSongs() );
Collections.sort( songsByDate, new UploadTimeComparator() );

List<Song> songsByLikes = new ArrayList<>( SongDAO.getInstance().getAllSongs() );
Collections.sort( songsByLikes, new LikesComparator() );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM