The output does not sort in ascending order. Here is the code and the output I am getting.
The actual output is:
Amy Jose Jeremy Alice Patrick Alan Amy Jeremy Helen Alexi
While the expected output is:
Amy, Alice, Jeremy, jose, Patrick Alan, Amy, Alexi, Helen, Jeremy
The code is:
public class MyFriends
{
static Set<String> names = new TreeSet<String>();
public MyFriends()
{
super();
names = new TreeSet<String>();
}
public static void exampleMethod()
{
String[] name1 = {"Amy", "Jose", "Jeremy", "Alice", "Patrick"};
String[] name2 = { "Alan", "Amy", "Jeremy", "Helen", "Alexi"};
for (int i = 0; i < name1.length; i++)
{
names.add(name1[i]);
}
for (String aString : name1)
{
System.out.print(" " + aString);
}
for (int i = 0; i < name2.length; i++)
{
names.add(name2[i]);
}
for (String bString : name2)
{
System.out.print(" " + bString);
}
}
You’re currently just writing out the arrays again… adding the contents of the array into a
TreeSetisn’t going to change the array.Instead of the two blocks writing out the arrays, you should have one, right at the end:
If you actually want two lines of output, you should use two
TreeSetinstances.If you want to sort the arrays, you should just sort them in place. When you add a value to a
TreeSet, it neither knows nor cares where it comes from. It’s just a reference to a string object (in this case).