4

Is it possible to do the following?

List<Object o, Object p> listWithTwoObjects;

I want to retrieve data from a database and save it into this list, concretely in this way

Query query = "retrieve all posts and username, which this user posted";
List<Object o, Object p> userAndPost = query.getResultList();

o is the username, and p is the post. I can then render this to my template and show each post with its user.

My question is about the List with two Objects inside. Is it possible and if yes, how and where is the documentation for this?


You can define a Pair class as follows:

public class Pair
{
    String username;
    int post;

    public Pair(String username, int post)
    {
        this.username = username;
        this.post = post;
    }
}

and then simply use List<Pair>, for example:

List<Pair> pairs = new ArrayList<Pair>();
pairs.add(new Pair("doniyor", 12345));

// ...

Pair p = pairs.get(0);
System.out.pritnln(p.username); // doniyor
System.out.pritnln(p.post); // 12345
4

3 回答 3

18

Pair您可以按如下方式定义一个类:

public class Pair
{
    String username;
    int post;

    public Pair(String username, int post)
    {
        this.username = username;
        this.post = post;
    }
}

然后简单地使用List<Pair>,例如:

List<Pair> pairs = new ArrayList<Pair>();
pairs.add(new Pair("doniyor", 12345));

// ...

Pair p = pairs.get(0);
System.out.pritnln(p.username); // doniyor
System.out.pritnln(p.post); // 12345
于 2012-07-05T08:54:54.557 回答
2

If i understand correctly you want to have all posts of a user, so instead of using List you should use Map:

Map<String,List<Post>> map = new HashMap<String,List<Post>>();

Then, the key(String) would be the userName and the value would be a list of Post objects.

于 2012-07-05T08:59:53.757 回答
1

You can't define a list like that, but you can use a Map, with username as key and post as value. Or is there a particular reason to use a list?

于 2012-07-05T09:01:00.317 回答