0

I want to store some values (actually a message) using list in Java. I want to store something like:

{user1, message, user2, time}
{user1, message, user4, time}
{user3, message, user1, time} 

I have declared an arraylist like this:

public List<List<String>> message = new ArrayList<List<String>>();

How can I add values in this list and how can I get a specific row (let's say the second row) of this list?

I've tried:

    message.get(0).add(msg, target,time);

but I get an error:

"The method add(String) in the type List is not applicable for the arguments (String, String, Integer)"

Galil
  • 859
  • 2
  • 16
  • 40
  • Please see [this stackoverflow question](http://stackoverflow.com/questions/1474954/working-with-a-list-of-lists-in-java) which your question duplicates. – ProgrammerDan Mar 05 '14 at 20:01
  • 1
    "*but I get an error*" what does error massage say? – Pshemo Mar 05 '14 at 20:01
  • The error is "The method add(String) in the type List is not applicable for the arguments (String, String, Integer) – Galil Mar 05 '14 at 20:10
  • @Galil It would be better to put information in your original post instead of of comment. This info is important and people who are reading your question shouldn't be forced to search for it in comments. You can do it wish [[edit]] option placed under your question. – Pshemo Mar 05 '14 at 20:18

2 Answers2

1

You could do something like:

List<Object[]> list = new ArrayList<Object[]>();        
Object[] ob = new Object[4];
ob[0] = "user1";
ob[1] = "messge1";
ob[2] = "user2";
ob[3] = "time1";

list.add(ob);       

ob = new Object[4];
ob[0] = "user2";
ob[1] = "messge2";
ob[2] = "user4";
ob[3] = "time2";
list.add(ob);

// Output the values
for(Object[] o : list){
    System.out.print(o[0] + "\t");
    System.out.print(o[1] + "\t");
    System.out.print(o[2] + "\t");
    System.out.print(o[3] + "\n");
}

and the output will be:

user1 messge1 user2 time1

user2 messge2 user4 time2
Mohammad Najar
  • 2,009
  • 2
  • 21
  • 31
  • I think this is almost what I'm looking for, but could you please tell me how can I get a specific value (eg message1) without the for-loop if possible. Moreover, how can I delete a specific row? – Galil Mar 05 '14 at 20:31
  • (list.get(0))[3] // returns time AND list.remove(0); removes the first {user1,msg,user2,time} record. – Mohammad Najar Mar 05 '14 at 20:35
0

by

message.get(0);

you are retriving the first list in list of list referred by message

List has add(T object) method so you can't pass all 3 Objects in one call, one way to do is

message.get(0).add(msg);
message.get(0).add(target);
message.get(0).add(time);
jmj
  • 237,923
  • 42
  • 401
  • 438