0

I have thhis few lines of code:

Set<Group> setofAllGroups;
setofAllGroups = new TreeSet<Group>();
Group[] allGroupsArray = (Group[]) setofAllGroups.toArray();

the last line causes a runtime error, in debug mode I get "Source not found"

the code for the class 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();
}

}

What is the reason for the runtime error ?

1

1 Answer 1

2

Quick answer is that you cannot cast like that:

Group[] allGroupsArray = (Group[]) setofAllGroups.toArray();

Instead you have to use this:

Group[] allGroupsArray = setofAllGroups.toArray(
     new Group[setofAllGroups.size()]);

That's because toArray() returns Object[] and after that you try to cast Object[] to Group[]. This fails.

Sign up to request clarification or add additional context in comments.

1 Comment

code works. can you expalin why toArray is reciving a parameter ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.