java 如何将 DefaultListModel 转换为 List<Object>?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1644756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 17:24:12  来源:igfitidea点击:

How to cast DefaultListModel into List<Object>?

java

提问by Ante

I have to put all elements from a DefaultListModel(in a listbox) into a List<Object>. How can I do that in Java?

我必须将 a DefaultListModel(在列表框中)中的所有元素放入List<Object>. 我怎样才能在 Java 中做到这一点?

回答by jarnbjo

Arrays.asList(model.toArray());

回答by Tom Hawtin - tackline

If you want to make a copy of the contents, then you can use DefaultListModel.toArrayto get the data and construct your favourite Listimplementation with that. Alternatively you can loop over ListModel.getElementAtListModel.getSizetimes.

如果您想复制内容,那么您可以使用DefaultListModel.toArray获取数据并List用它构建您喜欢的实现。或者,您可以循环ListModel.getElementAtListModel.getSize多次。

If you want a live connection between the collections rather than a copy, use AbstractList:

如果您想要集合之间的实时连接而不是副本,请使用AbstractList

 public static List<Object> asList(final DefaultListModel model) {
     return new AbstractList<Object>() {
          @Override public Object get(int index) {
              return        model.getElementAt(index);
          }
          ...
     };
 }

You may want to slide Class.castin there, but there is an inherent problem with Swing types not being generic.

您可能想Class.cast在那里滑动,但是 Swing 类型不是通用的存在一个固有的问题。

回答by Malaxeur

According to ye olde API, you'll need to use the elements()method and iterate over them, adding them to a list. DefaultListModelis not in the same hierarchy as the normal Collections classes.

根据 ye olde API,您需要使用该elements()方法并迭代它们,将它们添加到列表中。 DefaultListModel与普通的 Collections 类不在同一层次结构中。

OR use what jarnbjo suggested!

或使用 jarnbjo 建议的内容!