我有几行代码:
Set<Group> setofAllGroups;
setofAllGroups = new TreeSet<Group>();
Group[] allGroupsArray = (Group[]) setofAllGroups.toArray();
最后一行导致运行时错误,在调试模式下我得到“Source not found”
类Group的代码:
public class Group
{
String groupName;
Set<Recipient> groupMembers;
public Group()
{
groupName = "";
groupMembers = new TreeSet<Recipient>();
}
public void setGroupName(String name)
{
groupName = name;
return;
}
public void addMember(Recipient toAdd)
{
groupMembers.add(toAdd);
return;
}
public void addMember(String name, String phoneNumber)
{
Recipient toAdd = new Recipient(name, phoneNumber);
groupMembers.add(toAdd);
return;
}
public void removeMember(Recipient toRemove)
{
groupMembers.remove(toRemove);
}
public void removeMember(String name, String phoneNumber)
{
Recipient toRemove = new Recipient(name, phoneNumber);
groupMembers.remove(toRemove);
}
public void removeAllGroupMembers()
{
groupMembers.clear();
}
}
运行时错误的原因是什么?
答案 0 :(得分:2)
快速回答是你不能这样投:
Group[] allGroupsArray = (Group[]) setofAllGroups.toArray();
相反,你必须使用它:
Group[] allGroupsArray = setofAllGroups.toArray(
new Group[setofAllGroups.size()]);
那是因为toArray()返回Object [],之后你尝试将Object []转换为Group []。这失败了。