简体   繁体   中英

How to correctly specify a list in java

I am using Eclipse Juno and Java.

I want to create a list and then store that list in another list so I can pass the list of lists to the server side. I have tried:

ArrayList<T> listAccountAndCubs = new ArrayList<Comparable>();
listAccountAndCubs.add(accountId);
listAccountAndCubs.add(sqlDateArchived);

However, I can not get the values "T" and "Comparable" correct. I tried "String" however that does not work for storing the date.

Once the above is correct how do I set up the list to contain "listAccountAndCubs"?

Thanks for any assistance,

Glyn

this is how you can create a list

List<String> l = new ArrayList<String>();

this is how you can create list of list

List<List<Comparable>> listOfList = new ArrayList<List<Comparable>>();
listOfList.add(new ArrayList<Comparable>());
...

Sounds like you want something like this

List<List<String>> listAccountAndCubs = new ArrayList<List<String>>();

I would recomment using Google Guava library to clean the syntax a bit

List<List<String>> listAccountAndCubs = Lists.newArrayList();
List<ArrayList<Comparable>> listAccountAndCubs = new ArrayList<>();

or

List<String> l1=new ArrayList<>();
List<List<String>> l2=new ArrayList<>();

l1.add("a");
l2.add(l1); 

If I understand you crrectly you want to have a list of Strings, and store this in another list?

List<String> sl = new ArrayList<String>();
List<List<String>>sls = new ArrayList<List<String>>();
sls.add(sl);
sl.add("String 1");

The value "T" is just a placeholder for the type, as the list is a generic interface, which can take any arbitrary object.

If you want to create a list of unspecified types, you would use

List<?>list = new ArrayList<?>();

Then you can add untyped objects to it, but in your case this is not neccessary.

Instead you can of course also create a list of comparables. Like this:

List<Comparable<String>>list = new ArrayList<Comparable<String>>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM