输出不按升序排序。这是我得到的代码和输出。
实际输出是:
Amy Jose Jeremy Alice Patrick Alan Amy Jeremy Helen Alexi
预期输出为:
Amy, Alice, Jeremy, jose, Patrick Alan, Amy, Alexi, Helen, Jeremy
代码是:
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);
}
}
答案 0 :(得分:5)
你现在只是再次写出数组......将数组的内容添加到TreeSet
中不会改变数组。
而不是写出阵列的两个块,你应该有一个,就在最后:
for (String name : names)
{
System.out.print(" " + name);
}
如果实际需要两行输出,则应使用两个TreeSet
个实例。
如果要对数组进行排序,则应该对它们进行排序。当您向TreeSet
添加值时,它既不知道也不关心它来自何处。它只是对字符串对象的引用(在本例中)。
答案 1 :(得分:1)
我将其重写为:
public class MyFriends
{
// I just changed the name for testing purtposes
public static void main(final String[] argv)
{
final Set<String> names = new TreeSet<String>();
final String[] name1 = {"Amy", "Jose", "Jeremy", "Alice", "Patrick"};
final String[] name2 = { "Alan", "Amy", "Jeremy", "Helen", "Alexi"};
add(name1, names);
display(names);
// you wanted to display each array separately right, not the total of all names in both
// arrays
names.clear();
add(name2, names);
display(names);
}
private static void add(final String[] namesToAdd,
final Set<String> names)
{
for(final String name : namesToAdd)
{
names.add(name);
}
}
private static void display(final Set<String> names)
{
for(final String name : names)
{
System.out.print(" " + name);
}
System.out.println();
}
}
这可以避免传递错误变量的问题(正如Jon在他的回答中指出的那样),因为传递错误的东西会导致编译时错误。
制作重复代码的方法也是一个好主意 - 代码喜欢使用名称,并且通过将代码放入方法中,可以为代码块添加一个名称。
编辑: 为了跟上Jon的答案:-)这是我真正做到的方式,有两套:
public class Main
{
// I just changed the name for testing purtposes
public static void main(final String[] argv)
{
final Set<String> namesSet1;
final Set<String> namesSet2;
final String[] nameArray1 =
{
"Amy",
"Jose",
"Jeremy",
"Alice",
"Patrick"
};
final String[] nameArray2 =
{
"Alan",
"Amy",
"Jeremy",
"Helen",
"Alexi"
};
namesSet1 = makeSet(nameArray1);
display(namesSet1);
namesSet2 = makeSet(nameArray2);
display(namesSet2);
}
private static Set<String> makeSet(final String[] namesToAdd)
{
final Set<String> names;
names = new TreeSet<String>();
for(final String name : namesToAdd)
{
names.add(name);
}
return (names);
}
private static void display(final Set<String> names)
{
for(final String name : names)
{
System.out.print(" " + name);
}
System.out.println();
}
}
答案 2 :(得分:0)
您需要通过TreeSet
特殊Comparator
才能获得此订单:
Amy, Alice, Jeremy, jose, Patrick
Alan, Amy, Alexi, Helen, Jeremy
首先,Alice和Alexi都按照字母顺序来到Amy面前。另外,jose来自Patrick,因为它以小写字母开头(如果你想在订购时忽略大小写,请使用Comparator.CASE_INSENSITIVE_ORDER
或Collator
。)