• 0

getting values from ArrayList in Java


Question

Whats the strategy to get the "value" of a word if its in the ArrayList. like for instance i use a TreeMap to bag a whole document inside and use the arrayList as an indicator how many lines there are . like for example and is in line 1 2, 4, 6. so if we want to get the value (line number) of the word, how do we do it

Link to comment
Share on other sites

3 answers to this question

Recommended Posts

  • 0

Do you want to do something like print out all the line numbers it's on?

If so (assuming you're using 1.4.2 and not 1.5.0 and the spiffy generics):

ArrayList x = (ArrayList)myMap.get("and");

for (int i = 0; i < x.size(); ++i)

{

System.out.println(x.get(i));

}

Otherwise if you are using 1.5.0 and generics, no Cast needed and you can use iterators ;)

Link to comment
Share on other sites

  • 0

Edit: ^ beat me too it :)

I dont understand your question? ...Either

ArrayList list = new ArrayList();

list.add("A");
list.add("B");
list.add("C");
list.add("D");

Iterator it = list.iterator();

while (it.hasNext()) {
  String s = (String) it.next();
  System.out.println(s);
}

or

for (int i=0; i &lt; list.size(); i++) {
  String s = (String) list.get(i);
  System.out.println(s);
}

you can also use list.indexOf() or list.contains()

really it is all in the Java API

Edited by liykh001
Link to comment
Share on other sites

  • 0

Spice it up with 1.5.0 code


ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;();

list.add("A");
list.add("B");
list.add("C");
list.add("D");

for(String s : list)
   System.out.println(s);

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.