java,从treemap的数组列表值中删除一个方法中的对象

r1zhe5dt  于 2021-07-08  发布在  Java
关注(0)|答案(0)|浏览(260)

所以我有一个treemap,格式是treemap<string,list>。我有一个通用类消息,t可以是文本、语音或媒体类。item是消息的超类。我正在尝试删除treemap的每个列表值中属于media类的第一条消息。我的程序接受一个输入2来删除第一条媒体消息。但是当我输入1时,它列出了树Map值,当我显示它时,消息仍然存在。我知道我选择的第一条消息是媒体,因为我打印出来的消息之前删除它。我做错什么了?

public void run() {
      boolean res = true;
      do {

         System.out.println("1. List all accounts \n 2. Erase the first media" +
                 " message \n 3. equals Test \n 4. Quit \n\n Enter a choice " +
                 "(1-4)");
         Scanner scanner  = new Scanner(System.in);
         int choice  = scanner.nextInt();
         switch(choice) {
            case 1:
               this.listAccounts();
               break;
            case 2:
               this.eraseMedia();
               break;
            case 3:
               this.equalsTest();
               break;
            case 4:
               res = false;
               System.exit(0);
               scanner.close();
               break;

         }

      }while(res);
   }

   private void listAccounts() {
      String key = null;
      List<Item> value = null;
      Item element = null;

      System.out.println("List of All Accounts");
      for(Map.Entry <String, List<Item>> entry: treeMap.entrySet()) {
         double charges = 0;
         System.out.println("Account:" + entry.getKey());
         value = treeMap.get(entry.getKey());
         ListIterator<Item> iter = value.listIterator();
         while(iter.hasNext()) {
            element = iter.next();
            System.out.println(element.toString());
            charges += element.getCharge();

         }
         System.out.println("Total Charges: " + charges);
      }

   }

   private void eraseMedia() {
      List<Item> value = null;
      for(Map.Entry <String, List<Item>> entry: treeMap.entrySet()) {
         value = treeMap.get(entry.getKey());
         this.eraseHelper(value);

      }
   }

   private void eraseHelper(List<? extends Item> list) {

      for(Item element: list) {
         if(element instanceof Message<?>) {
            Message<?> message = (Message<?>) element;
            if(message.getMessage() instanceof Media) {
               System.out.println(message.getMessage());
               list.remove(message);
               break;
            }
         }
      }
   }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题