【问题标题】:adding a String from a String Array into an ArrayList将字符串数组中的字符串添加到 ArrayList
【发布时间】:2012-04-24 09:24:01
【问题描述】:
String [] words = { "apple", "orange", };
String Word = words[wordGenerator];            //wordsGenerator is just a rand(); which return a integer.

String [] letters;
List<String> wordList;

letters = new String[12];
wordList = new ArrayList<String>(Arrays.asList(letters));

letters = Word.split("(?!^)");

通过执行上述代码,我知道如果生成苹果,我将得到一个名为“字母”的数组,其中前 5 个内存为 a、p、p、l、e,对吗?

如果是这样,我如何将这 5 个字符串从“字母”数组传递到 wordList?解决方案似乎很简单,但我就是想不出来。任何帮助将不胜感激。谢谢你。

【问题讨论】:

    标签: java android arrays eclipse arraylist


    【解决方案1】:
     for(int i=0;i<letters.length();i++{
     wordlist.add(letters[i]);
     }
    

    我认为..这就是您要问的...?

    【讨论】:

    • 谢谢拉朱。够呛。 ;) 我将 add 改为 set 。 for(int i = 0; i
    【解决方案2】:

    这里是一个sn-p代码:

    /**
     * @param args
     */
    public static void main(String[] args) {
        //init the wordList
        List<String> wordList=new ArrayList<String>();
        //init the word buffer
        String [] letters = new String[12];
        //init the data
        String [] words = { "apple", "orange", };
        //pick a random number
        int wordsGenerator = new Random().nextInt(words.length);
        //pick a random word
        String Word = words[wordsGenerator];            
        //process the word...
        letters = Word.split("(?!^)");
        //add the word to the wordList
        String mergedWord = join(letters);
        wordList.add(mergedWord);
    
    }
    
    /*
     * Merges a set of strings to one string
     */
    static String join(String[] strs){
        StringBuffer sb=new StringBuffer();
        for (String item : strs) {
            sb.append(item);
        }
        return sb.toString();
    }
    

    }

    【讨论】:

      猜你喜欢
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      • 2016-08-02
      • 2011-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多