在指令中,我被要求「聲明一個接口類型來保存一個包含字符集作爲其鍵的映射,並將有序的字符串集作爲值」。所有這一次我一直在使用TreeSets。現在我不確定,我現在想用TreeMap來思考 。下面的代碼是我用過的演示TreeMap。首先可以按照上面的指令使用TreeSet而不是TreeMap。其次,當使用TreeMap for methodB()時,出現錯誤「非靜態變量名稱不能從靜態上下文中引用」?謝謝。TreeSet或TreeMap - 按指令
public class MyMates
{
private TreeMap names = new TreeMap();
private static String[] name1 = null;
private static String[] name2 = null;
private static String[] name3 = null;
public MyMates()
{
super();
names = new TreeMap();
}
public static void methodASet()
{
String[] name1 = new String[] {"Amy", "Jose", "Jeremy", "Alice", "Patrick"};
String[] name2 = new String[] { "Alan", "Amy", "Jeremy", "Helen", "Alexi"};
String[] name3 = new String[] { "Adel", "Aaron", "Amy", "James", "Alice" };
}
public static String methodB(String aTemp)
{
for (int i = 0; i < name1.length; i++)
{
names.add(name1[i]);
}
System.out.println(names);
for (int i = 0; i < name2.length; i++)
{
names.add(name2[i]);
}
System.out.println(names);
for (int i = 0; i < name3.length; i++)
{
names.add(name3[i]);
}
System.out.println(names);
return aTemp
}
public static void populateTable()
{
girlFriends myList = new girlFriends();
names.addAll(myList.getNames()); // same error here
}
首先,如果你被要求創建一個接口,我建議這樣做,而不是編寫實現。其次,'methodB'不能看到'name1','name2'和'name3',因爲它們的作用域是'methodASet'。 – Powerlord 2010-07-15 15:54:50