0

I'm trying to create a phone book using a 2D ArrayList based on user input. Here is my current code:

    ArrayList<ArrayList<String> info = new ArrayList<ArrayList<String>>();  
    ArrayList<String> entry = new ArrayList<String>();

    System.out.println("Enter first and last name: ");
    entry.add(addScan.nextLine());
    System.out.println("Enter Address: ");
    entry.add(addScan.nextLine());
    System.out.println("Add phone number: ");
    entry.add(addScan.nextLine());
    info.add(entry);  

This is inside a do-while loop that exits when the user is done entering contacts. I printed with System.out.println(info);
Here is the output when I printed:

    [[John Snow, 1234 King's Landing, 123-456-7890, Tyrion Lanister, 
    4567 Castle Black, 222-222-2222, Ned Stark, 999 Winterfell Lane, 
    777-777-7777], [John Snow, 1234 King's Landing, 123-456-7890, 
    Tyrion Lanister, 4567 Castle Black, 222-222-2222, Ned Stark, 999 
    Winterfell Lane, 777-777-7777], [John Snow, 1234 King's Landing, 
    123-456-7890, Tyrion Lanister, 4567 Castle Black, 222-222-2222, Ned 
    Stark, 999 Winterfell Lane, 777-777-7777]]

It correctly printed 3 elements but the elements it printed is the entire array instead of just the appropriate entry. Where am I going wrong? I tried running a for loop and using info.get(i).get(0) + info.get(i).get(1) + info.get(i).get(2), but to no avail. Any ideas will be helpful.

quazi_moto
  • 449
  • 1
  • 3
  • 14
  • post the code where you are printing the list. – NishanthSpShetty Dec 14 '17 at 07:02
  • The code you posted doesn't print anything from the list(s). Please provide a [mcve]. – shmosel Dec 14 '17 at 07:02
  • `ArrayList info = new ArrayList>(); ` 1. Here **>** is missing in `ArrayList` and 2. `new ArrayList>` could be written like `new ArrayList<>`, assuming you are using Java7 or higher. – vinS Dec 14 '17 at 07:03
  • Editted to add how I printed: System.out.println(info); – quazi_moto Dec 14 '17 at 07:13
  • Duplicate of [Why does my ArrayList contain N copies of the last item added to the list?](https://stackoverflow.com/questions/19843506/why-does-my-arraylist-contain-n-copies-of-the-last-item-added-to-the-list) – shmosel Dec 14 '17 at 07:17
  • Thank you @shmosel. That fixed it. Sorry for not showing print statement. First time posting on stackoverflow. – quazi_moto Dec 14 '17 at 07:21

0 Answers0