泛型:无法从Collections.emptyList()转换为List< String>

编程入门 行业动态 更新时间:2024-10-10 13:21:32
本文介绍了泛型:无法从Collections.emptyList()转换为List< String>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

为什么

public List< String> getList(){ if(isMyListOKReady())返回myList; 返回Collections.emptyList(); }

编译良好,但对于 public List< String> getList(){返回isMyListReady()? myList:Collections.emptyList(); }

Eclipse表示类型不匹配:无法从List< ; Object> to List< String>?

解决方案

>类型安全的空列表。

因此,返回像这样的空字符串列表

public List< ;字符串> getList(){返回isMyListReady()? myList:Collections。< String> emptyList(); $ b

更具体地说,看你的函数是否返回列表与LT;字符串> 。所以当你使用三元运算符时,你的条件也应该返回 List< String> 。

但是在 Collections.emptyList()的情况下,它的类型不是列表与LT;字符串> 。所以只需要指定空集合的类型。所以只需使用 Collections。< String> emptyList()。

Why

public List<String> getList(){ if (isMyListOKReady()) return myList; return Collections.emptyList(); }

compiles well, but for

public List<String> getList(){ return isMyListReady() ? myList : Collections.emptyList(); }

Eclipse says "Type mismatch: cannot convert from List<Object> to List<String>"?

解决方案

You need to take care of type safety of empty list.

So return the empty list of string like this

public List<String> getList(){ return isMyListReady() ? myList : Collections.<String>emptyList(); }

To be more specific, look you function is returning List<String>. So when you are using ternary operator then your condition should also return List<String>.

But in the case of Collections.emptyList() doesn't have it's type as List<String>. So Just need to specify the type of empty collection. So just use Collections.<String>emptyList().

更多推荐

泛型:无法从Collections.emptyList()转换为List&lt; String&gt;

本文发布于:2023-11-12 13:00:59,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   emptyList   泛型   Collections   List

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!