Returning ArrayList via user input
Lets say I have multiple ArrayLists
Code :
ArrayList<String> list01 = new ArrayList<String>();
ArrayList<String> list02 = new ArrayList<String>();
ArrayList<String> list03 = new ArrayList<String>();
ArrayList<String> list04 = new ArrayList<String>();
How would I be able to return a list that the user selects? I tried something like the following but it doesn't compile as I get an incompatible types error.
Code :
Scanner scanner = new Scanner(System.in);
int one = scanner.nextInt();
int two = scanner.nextInt();
ArrayList test = "list" + one + two;
System.out.println( test.size() );
Re: Returning ArrayList via user input
Code :
ArrayList test = "list" + one + two;
In Java - unlike PHP, say - you can't create variables like that.
Instead of (or as well as) using variables list01, list02 etc, put the lists into another collection: another list for instance. Then you can get the desired index in this list-of-lists from the user and extract the actual list they want to use.
You can hold the lists in any collection you find useful. Another alternative is a map whose keys can be used to identify the list the user wants to work with:
Code :
Map<String,List<String>> lists = new HashMap<String,List<String>>();
lists.put("name", new ArrayList<String>());
lists.put("address", new ArrayList<String>());
lists.put("phone", new ArrayList<String>());
System.out.println("Which list do you want? (name/address/phone)");
Scanner scanner = new Scanner(System.in);
String choice = scanner.nextLine().toLowerCase();
List<String> list = lists.get(choice);
Re: Returning ArrayList via user input
I see.
Is it possible to create a 2D array of ArrayLists? So the array item array[0][1] would return list01?
Re: Returning ArrayList via user input
Or to avoid bringing in another container, just use a switch statement, and return an ArrayList based on the control variable.
Re: Returning ArrayList via user input
Quote:
Is it possible to create a 2D array of ArrayLists?
Try it and see. It turns out you can't create what the compiler calls a "generic array" of ArrayList. That's why I used a collection (list or map).