Thomas W. Thomas W. - 9 months ago 51
Java Question

Converting ArrayList <T> to String[] does not take correct elements to put into the String[]

I have a method in a program that takes an ArrayList objects:

private ArrayList<T> list;

and subsequently can use this method to take all of the items, copy them to a String Array, and then remove the items from the original list.

Here is the method:

public String[] takeAll()
if (this.list.size() <= 0)
throw new NoSuchElementException("Unable to take elements from empty array list");
}//checks if list is empty

String[] targetArray;
targetArray = list.toArray(new String[list.size()]); //adds the Objects to the String[] targetArray


return targetArray;

Main that tests this:

public static void main(String args[])
SimpleList a;
a = new SimpleList(Position.FIRST, Position.LAST);
String[] b;
b = a.takeAll();
System.out.println("The String Array b contains: " + b);

When I run it, it returns something odd:

The String Array b contains: [Ljava.lang.String;@15db9742

What would I have to change to actually print out b where it should display {"thing1", "thing2", "thing3", "thing4"} ?

Answer Source

Try the Arrays.toString() method:

System.out.println("The String Array b contains: " + Arrays.toString(b));