java的数组静态方法头帮助的字符串参数

时间:2010-07-15 11:50:30

标签: java

我在名为methodASet的方法头中放置了字符串参数。是否可以在正文中使用此字符串参数并将参数中的单词作为集合返回?如果是这样,我该怎么做?谢谢。

public class MyMates {

private static Set<String> names;
private static String[] name1 = null;
private static String[] name2 = null;
private static String[] name3 = null;


public MyMates() {
    methodASet(); // (2) but I then get a error message "methodASet(java.lang.String) in myMates cannot applied to ()
    names = new TreeSet<String>();
}

public static void methodASet(String aTemp) {

    name1 = new String[]{"Amy", "Jose", "Jeremy", "Alice", "Patrick"};
    name2 = new String[]{"Alan", "Amy", "Jeremy", "Helen", "Alexi"};
    name3 = new String[]{"Adel", "Aaron", "Amy", "James", "Alice"};

   return aTemp; // (1) is it like this? 
}

2 个答案:

答案 0 :(得分:1)

您的方法methodASet()String作为参数,因此当您调用该方法时,必须将String传递给它。你试图在没有争论的情况下调用它。

public MyMates() {
    methodASet("something");
    // ...
}

此外,您的methodASet()方法为void,这意味着它不会返回值。所以你不能从方法中return aTemp;。删除return语句,或声明方法返回String

public static String methodASet(String aTemp) {
    // ...

    return aTemp;
}

答案 1 :(得分:1)

这就是如何将aTemp之类的字符串添加到现有集合中:

 static Set<String> names = new TreeSet<String>();

 public static void addToNames(String aTemp) {
   names.add(aTemp);
 }

您也可以使用一系列名称来执行此操作。我展示了简单的方法:

 static Set<String> names = new TreeSet<String>();

 public static void addToNames(String[] manyNames) {
   for(String name:manyNames)
     names.add(name);
 }

必须先创建Set才能添加任何值(否则您将获得NullPointerException)。 names被声明为静态字段,因此您可以在方法体内使用它,而不必返回它。

你可以像这样使用(第二种)方法:

public static void main(String[] args) {
   // assuming names is declared and constructed like shown above
   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"};

   addToNames(name1);
   addToNames(name2);
   addToNames(name3);

   // Prove that the set has no duplicates and is ordered:
   for(String name: names)
     System.out.println(name);
}

希望它有所帮助!