我试图在HashMap中存储和访问2种不同类型的List,并在调用返回HashMap的方法时对其进行访问,但是我收到此错误:
(new int[] {1,2, 3}).Contains(1)
该方法如下所示:
The constructor ArrayList<JournalArticle>(Object) is undefined
当我调用该方法并尝试将它们各自的值存储到新列表中时,我得到了之前注释过的错误:
public static HashMap<String, Object> getJournalArticles(long groupId) throws NumberFormatException, SystemException{
List<JournalArticle> journalArticles = JournalArticleLocalServiceUtil.getStructureArticles(groupId);
List<String> allJournalArticleIds = new ArrayList<String>();
for (JournalArticle journalArticle : journalArticles) {
allJournalArticleIds.add(journalArticle.getArticleId());
}
HashMap<String, Object> mapArticles = new HashMap<String,Object>();
mapArticles.put("journalArticles", journalArticles);
mapArticles.put("allJournalArticleIds", allJournalArticleIds);
return mapArticles;
}
怎么了?怎么解决?
答案 0 :(得分:2)
我将使用编写的类来保存此信息(使用Pair<L, R>
之类的书可能会更快):
class ArticleHolder {
private List<JournalArticle> journalArticles;
private List<String> allJournalArticleIds;
public ArticleHolder(List<JournalArticle> journalArticles,
List<String> allJournalArticleIds) {
this.journalArticles = journalArticles;
this.allJournalArticleIds = allJournalArticleIds;
}
//getters + setters
}
并更改您的方法:
public static ArticleHolder getJournalArticles(long groupId)
throws NumberFormatException, SystemException {
List<JournalArticle> journalArticles =
JournalArticleLocalServiceUtil.getStructureArticles(groupId);
List<String> allJournalArticleIds = new ArrayList<String>();
for (JournalArticle journalArticle : journalArticles) {
allJournalArticleIds.add(journalArticle.getArticleId());
}
return new ArticleHolder(journalArticles, allJournalArticleIds);
}
此外:您对new ArrayList<JournalArticle>(...)
的调用表明您打算创建新数组列表实例(假设代码可以编译)。即使您将地图值键入为Collection
个对象,也不必这样做。
答案 1 :(得分:1)
恕我直言,快速解决方案是将mapArticles的类型更改为此HashMap<String, List<?>>
,然后:
List<JournalArticle> allArticles = new ArrayList<JournalArticle>((Collection<JournalArticle>)mapArticles.get("journalArticles"));
List<String> allJournalArticleIds = new ArrayList<String>((Collection<String>)mapArticles.get("allJournalArticleIds"));
因为ArrayList构造函数仅支持以下选项:
new ArrayList<T>();
new ArrayList<T>(int capacity);
new ArrayList<T>(Collection<? extends T> collection);
Object
在编译时不是集合。