开发者

Loading a large of amounts of strings into my ArrayList, I dont want to clog up my class

I have a ArrayList and I want to put a lot of strings into it (several hundred) but I don't want to 开发者_高级运维code around a huge list of .add()'s and such. Can I important the strings from my strings.xml file into the ArrayList? If so, how?


If you have the values saved in strings.xml file you can simply do this:

ArrayList<String> values = new ArrayList<String>();
Collections.addAll(values, getResources.getStringArray(R.array.words));

or

List<String> values = Arrays.asList(getResources.getStringArray(R.array.words));


Here is an example of reading the "words.txt"file from the assets-direcytory in your project. Each word on a line by itself.

    /*
     *  If you know the number of words at compile time, 
     * specify it here in the initial capacity
     */
    ArrayList<String> words = new ArrayList<String>(50);  
    try {
        InputStream is = getResources().getAssets().open("words.txt");

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line;

        while((line = br.readLine()) != null)
        {
            words.add(line);
        }

        is.close();
    } catch (IOException e) {
        e.printStackTrace();
    }


Put the 100's of strings into a file and read from it. Iterate using a for loop to add these strings in. If you do not want to use a file, user String[] words = new String[]{"test","me"..."last word"} and then iterate over it.


If you have thousands of words, probably putting them into a txt file is a good solution. However, if the number of words are not that much you can do one more thing to avoid calling add() multiple times:

String[] myArray = {"stack", "oveflow", "java", "array",...}; //large array with lot of Strings.

List list = Arrays.asList(myArray);


If the xml file is in some specific format you can also easily read them all using dom4j

for example:

<?xml version="1.0" encoding="UTF-8"?>
<Root>
    <Address studentId="1001">
        <Details name="Sam" age="" sex="M" class="10" />
    </Address>
    <Address studentId="1002">
        <Details name="Krish" age="" sex="M" class="10" />
    </Address>
</Root>

you can read with this code:

String xmlFileName = "D:/validation/validator/src/summa/sample.xml";
  String xPath = "//Root/Address";
  Document document = getDocument( xmlFileName );
  List<Node> nodes = document.selectNodes( xPath );
  for (Node node : nodes)
  {
     String studentId = node.valueOf( "@studentId" );
     stringArray.add( studentId );
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜