-2
    ArrayList<String> nameList = new ArrayList<String>();
    nameList.add("James");
    nameList.add("Joe");
    nameList.add("Josh");
    nameList.add("Bob");
    nameList.add("Billy");
    System.out.println("The names are:\n " + nameList);

    nameList.remove(1);
    System.out.println("Find the index 1 and remove their name from the list:\n "+ nameList);

    nameList.size();
    System.out.println("Currently the ArrayList holds " + nameList.size() +
                        " names after removing the name of index 1" );

    String[] tempArray= new String[nameList.size()];
    tempArray = nameList.toArray(tempArray);

    System.out.println(tempArray); // I want it to display the values of the ArrayList

    }



}

The output I'm getting is [Ljava.lang.String;@4554617c when I want it to look like this [James, Josh, Bob, Billy]. New to programming would appreciate the help.

1 Answers1

0

A couple of things. Firstly, this code could be reduced.

String[] tempArray= new String[nameList.size()];
tempArray = nameList.toArray(tempArray);

could become

String[] tempArray= nameList.toArray(new String[nameList.size()]);

if I am not mistaken.

Secondly, an ArrayList automatically resizes itself with no code needed. How it does that is a whole new question.

And finally. The way objects are printed in Java is that if they are not primaries (int,bool,long,char...), they are printed using their .toString() method. On ArrayLists, this .toString() method returns a nice pretty representation of the list. But arrays don't define this method, and they instead get printed as some JVM dependent String. Instead, use Arrays.toString(tempArray) method. So your print statement would look like this:

System.out.println(Arrays.toString(tempArray));

Don't forget to import java.util.Arrays.

vikarjramun
  • 1,042
  • 12
  • 30
  • THANK YOU! I thought nobody was going to answer since my post kept getting voted down for some reason. – Trush Patel Sep 15 '17 at 01:25
  • @TrushPatel if you think this answer helped you please click the green check mark ✅ in the corner to show the community that this answer helped – vikarjramun Sep 15 '17 at 01:26
  • @TrushPatel Your post was downvoted because you could've easily found the solution yourself by googling 'java print array' the first post on google is the question that your question duplicates. – Oleg Sep 15 '17 at 01:35