Re: assignining an element from an ArrayList to a variable
On Sat, 8 Dec 2007 16:51:38 -0500, "Art Cummings" <aikiart7@gmail.com>
wrote:
Does anyone know how to assign an element from an ArrayList to a variable?
Yes.
Specifically, I know that I can print an item using
System.out.println(nameList);
Some items you can, others not.
but how do I assign the ArrayList element to a string variable?
String varble = myArrayList.get(i).toString();
Thanks
Arrt
[snip]
/**
This program demonstrates the ArrayList toString method.
*/
public class ArrayListDemo2
{
public static void main(String[] args)
{
// Create a vector to hold some names.
ArrayList nameList = new ArrayList();
Have you done generics in your classes yet? In other words, do you
know the difference between:
ArrayList nameList = new ArrayList();
and
ArrayList<String> nameListGeneric = new ArrayList<String>();
The first is an ArrayList of Objects the other is an ArrayList of
Strings. The two are different; only the second is a generic. When
you assign from the first ArrayList, the compiler only knows that it
contains Objects so you will need to explicitly use toString() to turn
the Object returned into a String.
String name = nameList.get(1).toString();
When you assign from the second ArrayList, the compiler knows that the
ArrayList<String> contains Strings, so it does not complain when you
assign the returned entry to a String.
String name = nameListGeneric.get(1);
String name;
// Add some names to the ArrayList.
nameList.add("James");
nameList.add("Catherine");
nameList.add("Bill");
// Now display the items in nameList.
System.out.println(nameList);
println takes a string parameter. You have passed it an ArrayList of
Objects. So println will implicitly call the toString() method on the
ArrayList you passed. Since you are attempting to demonstrate the use
of toString(), you might want to call it explicitly:
System.out.println(nameList.toString());
}
}