0

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

    list.clear();

    return targetArray;
}

Main that tests this:

    public static void main(String args[])
{
    SimpleList a;
    a = new SimpleList(Position.FIRST, Position.LAST);
    String[] b;
    a.list.add("thing1");
    a.list.add("thing2");
    a.list.add("thing3");
    a.list.add("thing4");
    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"} ?

Thomas W.
  • 3
  • 2
  • Side note: This code is a bit dangerous. Unless you're certain `T` is `String`, it can throw an `ArrayStoreException`. See the [javadoc](https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html#toArray(T[])) for more info. – shmosel Nov 23 '16 at 03:27

2 Answers2

-1

In Java, if you ask it to print an Object like that, it will print the toString() of that object. The easiest way to print the array elements is to run it through a for loop and print each element of array.

Brendan
  • 303
  • 1
  • 6
-1

Try the Arrays.toString() method:

System.out.println("The String Array b contains: " + Arrays.toString(b));
Ericson Willians
  • 7,606
  • 11
  • 63
  • 114